Assign value to class property inside class
I have the following code
class TopClass
{
public string ClsProp1 { get; set; }
public string ClsProp2 { get; set; }
public SubClass ClsProp3 { get; set; }
}
class SubClass
{
public string SCProp1 { get; set; }
public string SCProp2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
Test.TopClass TCN = new Test.TopClass();
TCN.ClsProp1 = "TCProp1--string value";
TCN.ClsProp2 = "TCProp2--string value";
TCN.ClsProp3.SCProp1 = "SCProp1--string value";
TCN.ClsProp3.SCProp2 = "SCProp2--string value";
}
}
I cannot figure out how to instantiate the TCN.ClsProp3.ScProp1 and TCN.ClsProp3.ScProp2 values. I keep getting "An unhandled exception of type 'System.NullReferenceException' occurred in Test.exe Additional information: Object reference not set to object instance." Error message. Forgive my ignorance, I am really trying to learn OOP from scratch.
Thank you in advance
source to share
You need to initialize the object ClsProp3
before you can use it.
TCN.ClsProp3 = new SubClass();
You can also initialize it in the constructor TopClass
like this:
class TopClass
{
public TopClass()
{
ClsProp3 = new SubClass();
}
public string ClsProp1 { get; set; }
public string ClsProp2 { get; set; }
public SubClass ClsProp3 { get; set; }
}
source to share
When training, it's best to choose a good domain. TopClass
s ClsPropX
do not bring a pleasant experience.
As for your original question, fire up the debugger and see what it means ClsProp3
. And keep in mind that it is not possible to assign anything to "nothing" that is null
in C #.
source to share