Search code examples
c#methodsparametersstaticref

c# static method with ref parameter - a good idea?


I recently refactored some code and now have a static utility class with a method like so:

const int x = 1;
public static string doWork(ref DataTable dt)
{
    decimal total = 0;
    foreach (DataRow row in dt.Select("COST_ID = " + x))
    {
        decimal annual = decimal.Parse(row["Cost"].ToString());
        total += decimal.Round(annual, 2);
    }
    return String.Format("{0:C}", total);
}

I've simplified the example for clarity...

Am I likely to experience any ill effects of doing this and putting a call to the doWork method in the code behind of an ASP.NET application being hit by many users? Anyone know or have a reference where I can read up on how, performance-wise, the static method will work? Does this become a bottleneck of any kind?

EDIT:

Yes I apologize this was not a very good example, so lets say something more like this:

const int x = 1;
public static string doWork(ref DataTable dt)
{
    foreach (DataRow row in dt.Select("COST_ID = " + x))
    {
        row["Cost"] = 0.0;
    }
}

You're saying that A) I don't actually even need the ref here, since Datatable is already passed by ref and B) The performance is not hit at all by "funneling" all calls to the single static method.


Solution

  • The ref keyword is not used for performance purposes. It is used when you would like to alter what a variable in another scope points-to (in simple terms). Your use of ref in this instance is extraneous, and likely to lead to problems in the future.

    My rule of thumb for ref is: if you are using it, you probably shouldn't be.

    Finally, to answer your question about performance: using ref will not change the performance envelope of the method on hand.


    After reading your edit, here are direct answers to your two questions:

    1. Correct, using ref is only going to cause confusion as this is not its intended usage (and it isn't used for performance).
    2. Correct, using a static method with a const ID variable is not likely to improve performance in any measurable fashion for your scenario.