Accessing class fields from a nested class [duplicate] - c#

This question already has answers here:
What fields can a nested class access of the class it's nested in?
(3 answers)
Closed 6 years ago.
What is the best way to access fields from a nested class?
class FirstClass
{
public int FirstClassField;
public FirstClass()
{
this.FirstClassField = 5;
}
class SecondNestedClass
{
int SecondClassField;
public SecondNestedClass()
{
FirstClassField = 6;
}
}
}
The error:
An object reference is required for the non-static field, method, or property 'FirstClass.FirstClassField'
The goal is to be able to use and modify FirstClass fields from the Nested class.
For my purposes, the first class is a form
public partial class MyForm : Form
And passing a reference of MyForm is not possible since it is readonly.
Any ideas?

The nested class is just a nested type, nothing like a nested instance. So if you create an instance of SecondNestedClass, there is no instance of FirstClass involved. So for which FirstClass instance do you want to set FirstClassField?
SecondNestedClass and FirstClass are completely different and independent types. FirstClassField is not a member of SecondNestedClass.
The only difference to non-nested types is that an instance of SecondNestedClass is allowed to access private fields of an instance of FirstClass. But you still need an instance at all to access its fields.
How to solve this depends on what you actually are trying to achieve. You could consider providing an instance of FirstClass to the constructor of SecondNestedClass:
public SecondNestedClass(FirstClass first)
{
first.FirstClassField = 6;
}

Related

Using “this” with a class name in C#

[Edit] What I wanted to ask was just putting a class name with this, so it wasn't about referencing an outer class member. Sorry for my inappropriate example!
[Edit2] Someone reported this as a duplicate BUT NOT! As I said earlier, I just wanted to know if it's possible to reference MyClass.this and this interchangeably like in Java. This wasn't a practical question at all but just for learning C# language itself. I don't mind removing this if people really think it's a duplicate so let me know.
In Java, you can use this with class names like this:
class OuterClass {
int outerMember = 1;
class InnerClass {
int innerMember = 2;
public void printOuterMember() {
System.out.println(OuterClass.this.outerMember);
System.out.println(outerMember);
}
public void printInnerMember() {
System.out.println(InnerClass.this.innerMember);
System.out.println(this.innerMember);
System.out.println(innerMember);
}
}
}
Sometimes class names are not needed, but sometimes helpful.
So I tried the same thing in C# but it seems it's impossible. Am I right?
C# does not support this, in Java the nested class captures the parent object reference. C# nested classes are more like static nested classes in Java. If you want access to the parent class you will need to pass a reference to it in the nested class constructor.
Nested classes will have access to private fields of the parent class if they have a reference to it, so you can achieve similar results, just the access to the parent class instance is not automatic as it is in Java. So this code works
class Owner
{
private int field;
class Nested
{
public Nested(Owner owner) { this.owner = owner; }
Owner owner;
public int D()
{
return owner.field;
}
}
}

create a private object for a class with private constructor in c# [duplicate]

This question already has answers here:
How to instantiate an object with a private constructor in C#?
(4 answers)
Closed 7 years ago.
I want to access some of the private members of a class which has its constructor defined as private. How do I create the PrivateObject for such class so that I can access its private members ?
I tried something like this but I cannot instantiate the class "MyClass1" so I am not able to instantite the PrivateObject.
MyClass1 myClass = new MyClass1(); //gives compilation error
PrivateObject po = new PrivateObject(myClass); //gives compilation error
Is there any workaround for this ?
Class with private constructor can only create itself from its own static method. For example:
class MyClass1
{
private MyClass1()
{
}
public static MyClass1 CreateInstance()
{
return new MyClass1();
}
}
It's private members like fields or properties are always accessible only from inside of the class (unless you make some tricks with reflection). If the field is protected you can access it by deriving from this class. All other way it's by design created to restrict access to those fields and you should not try accessing them from the outside.
Edited: now I noticed you use PrivateObject class which is created to make reflection trickes mentioned above. So now you only need to create instance. You should check what is the designed way of initializing this object probably by some static method?
Or check this link for more hacks with reflaction and using Activator: http://www.ipreferjim.com/2011/08/c-instantiating-an-object-with-a-private-constructor/

C# nested class properties

In C#, why does a nested class have to instantiate it's parent class, to reference its parent class non-static properties in code?
public class OuterClass
{
public int OuterClassProperty
{
get
{
return 1;
}
}
public class InnerClass
{
public int InnerClassProperty
{
get
{
/* syntax error: cannot access a non-static
* member of outer type via nested type.
*/
return OuterClassProperty;
}
}
}
}
It seems I have to do this instead:
public class OuterClass
{
public int OuterClassProperty
{
get
{
return 1;
}
}
public class InnerClass
{
public int InnerClassProperty
{
get
{
OuterClass ImplementedOuterClass = new OuterClass();
return ImplementedOuterClass.OuterClassProperty;
}
}
}
}
I'm thinking the first code example should be okay, because if InnerClass is instantiated, the parent class would implemented first - along with the parent class properties.
Thanks for the help, I'm trying to learn the in's and out's of C#... and I am not familiar with Java, comparing to Java won't help much...
The behavior you are observing is explicitly spelled out in the C# specification. Snippet of C# 5.0 below:
10.3.8.4 this access
A nested type and its containing type do not have a special relationship with regard to this-access (§7.6.7). Specifically, this within a nested type cannot be used to refer to instance members of the containing type. In cases where a nested type needs access to the instance members of its containing type, access can be provided by providing the this for the instance of the containing type as a constructor argument for the nested type.
The behavior of nested classes in C# is different for other language like Java inner classes in c# and C+ because C# is different language created by different language design team. Exact historical reasons why particular behavior was selected possibly could be found in blogs of members of C# design team, .Net design guidelines book or MSDN articles.

Access to private members of class [duplicate]

This question already has answers here:
Why are private fields private to the type, not the instance?
(10 answers)
Closed 9 years ago.
public class Class1
{
private object field;
public Class1(Class1 class1)
{
this.field = class1.field;
}
private void Func(Class1 class1)
{
this.field = class1.field;
}
}
This code compiles and works. But why? I always thought that private members are only accessible within the class scope. Also MSDN says so:
The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared
That's because by marking it as private, you are telling the compiler that only Class1 may access that variable. Even though your constructor is public, the variable itself is still declared within Class1 and so it has access to modify it.
Even though they could be two different instances, they are the same variable declaration.
However, if I did this from Class2, it would not work:
Class1 c1 = new Class1();
c1.field = "value"; // Won't compile
This is actually explained from your quote:
Private members are accessible only within the body of the class
The private keyword means its private for the class (as stated in MSDN), not the object. So one instance of a class can access the private members of another instance of the class.
It works because an object can hold anything. If you pass in class1 and the object field is null then the object field will remain null. If that makes sense?
As long as the code that access that private field is in Class1, you can use it. That's what private means - it's accessible from anywhere inside those {}

How to access variable of an Outer class in the inner class in c# [duplicate]

This question already has answers here:
What's the best way of accessing field in the enclosing class from the nested class?
(9 answers)
Closed 10 years ago.
i have two class i need to declare a variable common to both the classes..
In case of Nested classes i need to access the Outer class variable in the inner class
please give me a better way to do this in c#.
Sample code
Class A
{
int a;
Class B
{
// Need to access " a" here
}
}
Thanks in advance
First suggestion is to pass a reference to the Outer class to the Inner class on construction, so Inner class that then reference Outer class properties.
public Class Class_A
{
int a;
public Class Class_B
{
Class_A instance;
public Class_B(Class_A a_instance)
{
instance = a_instance;
}
void SomeMethod()
{
int someNumber = this.instance.a;
}
}
}
From your example, you probably need to pass a as a parameter to B in it's constructor - there's not way to access it otherwise. Having this as a 'child' class may not be a great design, however, but there's not enough information to really know either way.

Categories

Resources