Marcus
Marcus

Reputation: 11

Null Dereference C#

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?

Upvotes: 0

Views: 12350

Answers (2)

bbsimonbb
bbsimonbb

Reputation: 29002

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

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300599

Assuming ddl can never be null:

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

}

Otherwise:

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

}

Upvotes: 4

Related Questions