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

11,010

Solution 1

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.

Solution 2

The only time you ever need to pass a reference type (such as Datatable) by ref is if you plan on assigning the parameter to a new instance of a class. Ref is not needed in this case. Pass it by value.

Solution 3

AFAIK static methods are not slower than the instance ones. On the contrary, they actually may be slightly faster, because you don't need to pass the hidden this and possibly do a virtual call.

Solution 4

For your method the "ref" keyword is not required.

Solution 5

DataTable is already passed as reference, so ref is not needed

Share:
11,010
mikey
Author by

mikey

Updated on June 04, 2022

Comments

  • mikey
    mikey about 2 years

    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.