简体   繁体   中英

Is a C# null check required prior to casting an object with "as"?

I've only been able to find solutions on SO for Java/ActionScript tags. If this is a duplicate please let me know and I'll delete.

Using ASP.Net MVC 5, I'm passing a model class from ViewBag to a partial view in which it renders to a form:

@if (ViewBag.CourseQuoteRequest != null && ViewBag.CourseQuoteRequest as CourseQuoteRequest != null)
{
    <div>
        @Html.Partial("~/Views/Partial/_CourseQuoteRequest.cshtml", (CourseQuoteRequest) ViewBag.CourseQuoteRequest)
    </div>
}

Can the null checks be reliably simplified to only check for null once? It's important (to us) that the ViewBag model exists, and is only rendered if the partial view if it is the correct class type:

@if (ViewBag.CourseQuoteRequest as CourseQuoteRequest != null) // Acceptable and reliable?

The above runs, but I'm not sure if there's any risks that are being introduced.

You can simplify your null check by using the is operator

@if (ViewBag.CourseQuoteRequest is CourseQuoteRequest)

Also if you need the course quote request object, you can use pattern matching

@if (ViewBag.CourseQuoteRequest is CourseQuoteRequest request)
{
    <div>
        @Html.Partial("~/Views/Partial/_CourseQuoteRequest.cshtml", request)
    </div>
}

See here for documentation

as is null -safe :)

If you pass null to as it will return null .

But it can be even more simplified with is operator:

if (ViewBag.CourseQuoteRequest is CourseQuoteRequest courseQuoteRequest)

and under the if you can safely use courseQuoteRequest , which will be of type CourseQuoteRequest .

@if (ViewBag.CourseQuoteRequest is CourseQuoteRequest courseQuoteRequest)
{
    <div>
        @Html.Partial("~/Views/Partial/_CourseQuoteRequest.cshtml", courseQuoteRequest)
    </div>
}

See type pattern .

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