Thursday, June 06, 2019

C# Gotcha - "static readonly" v "const"

On the face of it, there seems very little difference between these, apart from one takes longer to type out.  However, there is one difference that could easily catch you out: you can reference a "static readonly" from pretty much anywhere in your code, but until your code gets to the line where it is declared, it will have the default value (typically zero for numbers).

Time for an example:-

public static readonly int size = width * height;
public static readonly
int width = 100;
public static readonly
int height = 50;

public void Test() {
    Console.WriteLine($"The size is {size}");
}

Yes, this program will output "The size is 0".  Probably not what you wanted.

No comments: