static field in abstract class not intializing



05-19-25 17-19-26
it appears that declaring and initializing a static reference type compiles ok is not initializing at run time. a silent but deadly bug. im not sure to initialize these fields in the class constructor or hard code the initial values into property accessor. since in this case is need hard code the value.
 
Last edited:
Please show us your code in code tags, not as screenshots.

If possible post some minimal code that demonstrates the problem.
 
The following code works just fine. It correctly prints out "Color [Green]" due to line 11. If you uncomment line 1, then line 9 will be use instead of line 11, and the output is "Color [Empty]".

C#:
// #define DO_NOT_INIT

using System;
using System.Drawing;

abstract class Vehicle
{
#if DO_NOT_INIT
    protected static Color s_color;
#else
    protected static Color s_color = Color.Green;
#endif
}

class Boat : Vehicle
{
    public Boat()
    {
        Console.WriteLine(s_color);
    }
}
                   
public class Program
{
    public static void Main()
    {
        var boat = new Boat();
    }
}

 
Last edited:
You might be in the situation where there is bug where you overwrite the value of the static field like in the case of the F117 class here.
C#:
using System;
using System.Drawing;

abstract class Vehicle
{
	protected static Color s_color = Color.Green;
}

class Boat : Vehicle
{
	public Boat()
	{
		Console.WriteLine(s_color);
	}
}

class F117 : Vehicle
{
	public F117()
	{
		s_color = Color.Black;
		Console.WriteLine(s_color);
	}
}
					
public class Program
{
	public static void Main()
	{
		var boat = new Boat();
		var f117 = new F117();
		var boat2 = new Boat();
	}
}
Which results in the output of:
Code:
Color [Green]
Color [Black]
Color [Black]

 
And the way to protect yourself from that kind of evil is to mark the field as readonly. Make line 6:
C#:
protected static readonly Color s_color = Color.Green;
so that you'll get a compilation error for line 21:
Code:
Compilation error (line 21, col 3): A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
 
Back
Top Bottom