First of all, please read through the question before concluding it is a dup of Member '<method>' cannot be accessed with an instance reference.
Now, my question is different because my Static Member is another class:
using System;
public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { Console.WriteLine("Driving"); }
// public static event bool RunOutOfGas;
// Other non-static fields and properties...
}
class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;
public static Automobile A1;
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
A1 = new Automobile();
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Automobile");
Automobile.Drive();
Console.WriteLine(Automobile.NumberOfWheels);
Console.WriteLine("SimpleClass");
Console.WriteLine(SimpleClass.A1.NumberOfWheels);
Console.WriteLine(SimpleClass.Automobile.NumberOfWheels);
}
}
Either SimpleClass.A1.NumberOfWheels
or SimpleClass.Automobile.NumberOfWheels
(or even SimpleClass.NumberOfWheels
), will give me errors.
How to access A1.NumberOfWheels
under SimpleClass
?
Conclusion: So if you use a static class instead of a C# simple type, there will be no way to access its static members (A1.NumberOfWheels
) under the root class (SimpleClass
), due to the limitation C# Static Members access rule. I ask the question because I think it is an obvious design defect, however, nobody address this specific issue and quickly swipe it under the carpet.
Probably the larger question is just that: What, exactly, are you trying to do?
@RufusL, good question. My understanding of the static variable or its purpose, is to share a single-point of truth among all its class objects. Using a very simple example to explain it, suppose I have a bunch of single-digit multiplier objects, which are in charge of calculating multiple of two single-digit numbers. The fastest way is not to calculate it each time but to store a two-dimension single-digit multiple table in their static variable, so no real multiple is needed, only lookup. This will dramatically increase the performance.
Now,
- it doesn't make sense that such static variable can only be C# predefined simple types, and can't be my own defined types.
- Neither it make much sense that such static variable within a class can only be one level deep, and can't get any deeper.