Reputation: 119
If I write
public MyObject TheObject {get; set;}
and later try to access myClassObject.TheObject.SomeProperty;
if TheObject
is null I get a NullReferenceException. But how I can declare the TheObject
properties to avoid an NRE if TheObject
can be null or have a default value.
Not sure if I explain correctly what is my concern. Here is what I'm trying to do safely. What is the best practice to do that.
class PowerfullPin
{
public string Id { get; set; }
}
class Test
{
public PowerfullPin PowerfullPin { get; set; }
}
class Main
{
Main()
{
Test Test = new Test();
//If PowerfullPin was not define it throws a NullReferenceException
System.Diagnostics.Debug.WriteLine(Test.PowerfullPin.Id);
}
}
Upvotes: 1
Views: 103
Reputation: 13960
Try with null conditional operator if using c# 6 or above. It's used to test for null before performing a member access (?.) or index (?[) operation.
class PowerfullPin
{
public string Id { get; set; }
}
class Test
{
public PowerfullPin PowerfullPin { get; set; }
}
class Main
{
Main()
{
Test Test = new Test();
System.Diagnostics.Debug.WriteLine(Test.PowerfullPin?.Id);
}
}
Upvotes: 4
Reputation: 1324
You are accessing property of a null object. PowerfullPin in Test class is null when you create object of Test.
So instead you can do like
Test test = new Test();
//While creating object of Test class you will have PowerfullPin
//property but it has not been initialized. That means it is null.
//You can not have properties of null object.
test.PowerfullPin = new PowerfullPin{
Id = 1,
SomeOtherProperty = "Value"
};
System.Diagnostics.Debug.WriteLine(test.PowerfullPin.Id);
Upvotes: 1