Null Dereference C#

11.4k 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 best solutions below

3
On

Assuming ddl can never be null:

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

}

Otherwise:

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

}
0
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.
}