Tuesday, March 1, 2016

Const and Static in C#

I learned the true difference between const and static in C# when it comes to class members. This did not come the hard way, but through a PluralSight course. I'm thankful for that!


Here's the difference:


const - set during compilation time, it seems like it is inlined. In other words if you have a const FEET from a class Yard like so:


class Yard
{
public const int FEET = 3;
}


and you use it like this:


...
var bar = baz * Yard.FEET;
...


You would be ok if Yard was in the same assembly, but if it's in another assembly and Yard.FEET changes, but the calling assembly doesn't get recompiled it'll still have its old value. Plus a const cannot be changed once compiled so you cannot compute it from something else like a config value.


With a static readonly member, you gain the benefit of computing the value at runtime AND if it the value changes (either by config or by code) and is in a separate assembly from the consumer (think GAC here) your calling code will retrieve the the new value.


Why use a constant ever? It's a bit more efficient during runtime since it gets inlined and saves a call. But let's be honest here, if you are using C# is that minor gain in efficiency really worth it? If that bit of performance makes a difference in your world, wouldn't you be using C or C++ instead? I'm sure a case can be made, but its not likely doing to be one unless you have millions of calls for the same thing. In that case there may be other optimizations that come first. Just saying...

No comments:

Post a Comment