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?
>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: