Search code examples
c#klocwork

Null reference '#as(test, 0)' that comes from line 28 will be dereferenced at line 28


I have below classes,

public class Test1
{
    public Test2 Test2 { get; set; }
}

public class Test2 { }

Now I have below method,

private void Test()
    {
        var test = ConfigurationManager.GetSection("Test");

        if (test != null)
        {
            var a= (test as Test1).Test2;
        }
    }

Now I am getting Klockwork error saying,

Null reference '#as(test, 0)' that comes from line 28 will be dereferenced at line 28

What this error mean and how to resolve it?

Note that this is Klockwork error, however C# compiling will not have any error.

Error at below line of code,

var a= (test as Test1).Test2;


Solution

  • It will compile but theres a chance with as that the resulting value could be null. You can ensure that it won't throw this way:

        var test = ConfigurationManager.GetSection("Test") as Test1;
    
        if (test != null)
        {
            var a = test.Test2;
        }