Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi!

I have next situation:
In ClassA I created an variable of type MyClass
C#
public class ClassA
{
    public MyClass var { get; set; }
    public class MyClass
    {
        public string user { get; set; }
        public string pass { get; set; }
    }
}

static void Main(string[] args)
{
    ClassA variable = new ClassA();
    variable.var.user = "TestUser";
    variable.var.pass = "testpass";  
}

When I try to set variable.var.user with any string value it gives me the error :

Terminal
System.NullReferenceException: 'Object reference not set to an instance of an object.'


What I have tried:

C#
public class ClassA
{
    public MyClass var { get; set; }
    public class MyClass
    {
        public string user { get; set; }
        public string pass { get; set; }
    }
}

static void Main(string[] args)
{
    ClassA variable = new ClassA();
    variable.var.user = "TestUser";
    variable.var.pass = "testpass";  
}


How the assigning should be made ?
Posted
Updated 21-Oct-22 3:39am

1 solution

I am not sure why you have a second class inside ClassA. But you need to instantiate the var variable before you can reference it. So add a constructor to ClassA as follows:
C#
public class ClassA
{
    public MyClass var { get; set; }
    public class MyClass
    {
        public string user { get; set; }
        public string pass { get; set; }
    }
    public ClassA()
    {
        var = new MyClass(); // create the MyClass object
    }
}



[edit]

Well it all depends on exactly what you are trying to do. But as far as I can see you only need one class and that is MyClass, so you can get rid of ClassA.
C#
public class MyClass
{
    public string user { get; set; }
    public string pass { get; set; }
}

Then all you need in your main method is:
C#
MyClass var = new MyClass(); // create the MyClass object
var.user = "TestUser";
var.pass = "testpass";


[/edit]
 
Share this answer
 
v2
Comments
Gaby94 21-Oct-22 9:46am    
Now it's working. Thanks. Should I move MyClass outside of ClassA?
Richard MacCutchan 21-Oct-22 10:11am    
See my updated solution.
Gaby94 24-Oct-22 2:55am    
That was just an example, my code is much longer than that.

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