Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"An object reference is required for the non-static field, method, or property" for nested classes accessing parent class fields

Lets say that I have the following C# code:

public class Foo
{
    public string someString;

    public class Bar
    {
        public string ReturnSomething()
        {
            return someString;
        }
    }
}

I assumed that an inner class could access state from its parent class, but when I try, I get the following error:

[CS0120] An object reference is required for the non-static field, method, or property 'Foo.someString'

Changing someString to static does resolve the error, but I don’t want to mark fields as static for this instance. Are there anymore workarounds for this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

C# (unlike Java for example, see Nested Classes in Java) does not associate instance of inner class with some instance of the outer, the main difference compared to usual classes is that in C# nested class can access internal members of enclosing one (static or instance when instance is provided). So you need to provide an instance in some way:

public class Foo
{
    private string someString;

    public class Bar
    {
        public string ReturnSomething()
        {
            return new Foo().someString;
        }
    }
}

Or

public class Foo
{
    private string someString;

    public class Bar
    {
        public string ReturnSomethingFromFoo(Foo f) => f.someString;
    }
}

If you want the "associated" behavior you will need to manually provide corresponding ctor and store associated instance:

public class Foo
{
    private string someString;

    public class Bar
    {
        private Foo _foo;

        public Bar(Foo f) => _foo = f;

        public string ReturnSomethingFromFoo(Foo f) => _foo.someString;
    }
}

See also:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading