C# – Why Shouldn’t an Object Reference Access a Static Member?

cobject-orientedobject-oriented-designstatic

Context of my question:

  1. I am reading C#.
  2. Trying to understand Static keyword.
  3. I understand that when Static is applied to a member of a class, it can only be modified by the class and not the class object references.

I will take an example here.

public class BluePrint
{
   public static string BluePrintCreatorName;
}

If I need to know the BluePrintCreator's Name, I can call

BluePrint.BluePrintCreatorName;

But if a house that is created from the blueprint wants to know the BluePrintCreator's Name, it does not have access.

BluePrint NewHouse = new BluePrint();
NewHouse.BluePrintCreatorName; //This is not accessible

Compiler error says:

Member 'AccessModifier.BluePrint.BluePrintCreatorName' cannot be accessed 
with an instance reference; qualify it with a type name instead 

I understand this is the way it works. But I want to know the basic concept to why Static keyword was required at all?

What will go wrong if a class object reference would have access to the static member?

Best Answer

Nothing go wrong for accessing a static member from an instance, in fact this is perfectly possible in other languages like java, your example code compiles and runs ok if its in java.

It's a check the compiler designers have introduced because they thought that this will help programmers to write clear code with this language. On this way only looking at the code you can always know if you are accessing a static or an instance member, in languages where this access is allow (like java) sometimes its a little confusing when someone decides to access a static member throughout an instance variable, in fact normally when you see this access in java code its more a mistake than a programmer really using this "language feature".

In my opinion limiting this access its a good decision in C# to avoid some mistakes and bad interpretations.

Although it's legal in Java to refer static members that way, it's recommended against in Code Conventions (10.2 Referring to Class Variables and Methods):

"Avoid using an object to access a class (static) variable or method. Use a class name instead..."