简体   繁体   中英

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?

Assuming ddl can never be null:

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

}

Otherwise:

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM