blog.mha.dk
The on-line blog of Michael Holm Andersen

ViewData and the null-coalescing operator

Wednesday, 30 December 2009 08:12 by mha

If you’re using ASP.NET MVC and are using the ViewData collection you might want to familiar yourself with the ?? operator.

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

Knowing this we can use the below syntax to e.g. display the title of a page in the browser with a value from ViewData and if this is null instead display a default value.

<%= ViewData["title"] ?? "Home Page" %>

MSDN has more info about the ?? operator.

Categories:   C# | ASP.NET MVC
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed
Comments are closed