Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Context of my question: I am reading C#. Trying to understand Static keyword. I

ID: 644475 • Letter: C

Question

Context of my question:

I am reading C#.
Trying to understand Static keyword.
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?

Explanation / Answer

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

Its a check the compiler designers introduce because they think this helps programmers to write clear code with this language. 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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote