SunLiker67
SunLiker67

Reputation: 119

How do I avoid NullReferenceExceptions?

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

Answers (2)

Oscar
Oscar

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.

https://learn.microsoft.com/en-us/dotnet/articles/csharp/language-reference/operators/null-conditional-operators

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

Bhuban Shrestha
Bhuban Shrestha

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

Related Questions