Member Cannot Be Accessed With An Instance Reference ; Qualify It W

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.

Đang xem: Member cannot be accessed with an instance reference

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.

Read more: how to merge wow accounts

BluePrint NewHouse = new BluePrint();NewHouse.BluePrintCreatorName; //This is not accessibleCompiler 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?

c# object-oriented object-oriented-design static
Improve this question
edited May 23 “17 at 12:40


asked Jul 4 “14 at 9:02


16111 silver badge66 bronze badges
Add a comment |

3 Answers 3

Active Oldest Votes
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.

Read more: Wow Essence Of The Cursed Protector, Essence Of The Cursed Protector

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…”

Leave a Comment