Null Dereference C#

11.3k views Asked by At
if (ddl.SelectedValue != "")

After using Fortify to analyze my code, Fortify show me a vulnerability which is "Null Dereference".

How can i resolve this issue?

2

There are 2 answers

3
Mitch Wheat On

Assuming ddl can never be null:

if (!String.IsNullOrEmpty(ddl.SelectedValue)
{

}

Otherwise:

if (ddl != null && !String.IsNullOrEmpty(ddl.SelectedValue)
{

}
0
bbsimonbb On

In C# 6 you have the null dereferencing operator, also called safe navigation operator, so you can do...

if (!String.IsNullOrEmpty(ddl?.SelectedValue)
{
    // ddl can be null and this will not throw.
}