Click here to Skip to main content
15,888,968 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Why is it when I do something as follows:

C#
public readonly string _objectString = ExtNameSpace.StaticClass.MyVar;

where MyVar is defined inside the static class StaticClass as

public static readonly string MyVar


I get the following error:

An object reference is required for the nonstatic field, method, or property

I was expecting this to happen the other way around, ie if I am assigning an object variable to a static member variable.
Posted
Comments
Firo Atrum Ventus 11-Oct-11 22:52pm    
Please post the actual code and the line which the error occurred.

You just need to understand how instance (non-static) methods work; which is one of the starting point to get before to understand OOP.

Please see my past solution where I explain it in a pretty detailed manner: What makes static methods accessible?[^].

—SA
 
Share this answer
 
I'm unable to reproduce this behavior in .NET 4.0. Which version of .NET are you using ?

The only scenario I can think of that would produce the error message you report is if you tried to define MyVar the way it is now (non-static) inside another class which is static.

If that's the case then simply change 'MyVar's declaration to:
public static readonly string _objectString = ExtNameSpace.StaticClass.MyVar;
If that's not an answer, please show a selection of your code at the place where the variable _objectString is defined, and the declaration for the class it occurs in.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900