Question

How can I use a non static variable in another class? Here's my problem:

public class class1
{
    int a;
    public int alpha{ get { return a; } }
    public void Method1()//method gets called...
    {
        a++;
    }

    public class class2
    {
       // Here initializing class2 variable as class1 property value.
        int b=alpha;
    }
}

Then Visual Studio comes up with: an object reference is required....

I must be really stupid as I have seen many examples of this on the internet but I don't get it working, so I would be thankful if anyone helped me.

Was it helpful?

Solution

You need access to object of that other class - in other words 'reference' (in your example class1)

var c1 = new class1();

then you can access it's members

var alpha = c1.alpha;

Depending on your project you can instantiate it inside class2 or pass it as a parameter to class2 constructor.

What you did here probably would work in JAVA.

OTHER TIPS

In order to use a non-static field (in fact, to use a non-static anything) you need to have an instance of the object from which you want to access a non-static member.

In this case, the nested class class2 needs to have a reference to its outer class. This could be passed in a constructor, or in a method call.

For example, here is one way of making it work:

public class class1
{
    int a;
    public int alpha{ get { return a; } }
    public void Method1()
    {
        a++;
        class2 c2 = new class2(this);
        Console.WriteLine("{0}", c2.b);
    }
    public class class2
    {
        public int b;
        public class2(class1 outer) {
            b = outer.alpha;
        }
    }
}

In your example, you'd need to instantiate an instance of class1 to access it's variables in class2.

it should be like this

public class class1
{
    int a;
    public int alpha{ get { return a; } }
    public void Method1()//method gets called...
    {
        a++;
    }     
}

public class class2
{
   // Here initializing class2 variable as class1 property value.
    class1 obj = new class1();
    int b= obj.alpha;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top