Introduction
This article demonstrates one of interesting and most useful concept in C#.
Question: What is Null Coalescing Operator?
In simple terms "This operator is used to handle a variable when value is null,
instead by perform an expected operation when value is null. The left side
operand will be executed when value is not null else in null case will return
right operand".
Step 1: Create a new web application
Step 2: The complete code of WebForm1.aspx looks as below
<%@
Page Language="C#"
AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs"
Inherits="NullCoalescingOperatorApp.WebForm1"
%>
<!DOCTYPE
html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head
id="Head1"
runat="server">
<title></title>
</head>
<body>
<form id="form1"
runat="server">
<div>
<h1
style="text-align:
center; font-family:
Verdana; font-size:
large; color:
Maroon">
Null Coalescing
Operator App</h1>
<center>
<table>
<tr>
<td
colspan="2"
align="center">
<asp:Button
ID="Button1"
runat="server"
Text="Addition"
Width="165px"
Font-Names="Verdana"
BackColor="Orange"
OnClick="Button1_Click"
/>
</td>
</tr>
</table>
<table>
<tr>
<td
colspan="2"
align="center">
<asp:Label
ID="lblResult"
runat="server"
Font-Names="Verdana"
ForeColor="Brown"></asp:Label>
</td>
</tr>
</table>
</center>
</div>
</form>
</body>
</html>
Step 3: The complete code of WebForm1.aspx.cs looks as below
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
namespace
NullCoalescingOperatorApp
{
public partial
class WebForm1 : System.Web.UI.Page
{
protected void
Page_Load(object sender,
EventArgs e)
{
}
protected void
Button1_Click(object sender,
EventArgs e)
{
//When Value is NULL
//int? a = null;
//int b = a ?? 0;
//lblResult.Text =
string.Format("Result is: {0}", b.ToString());
//When Value is NOT NULLint? a = 10;int
b = a ?? 0;lblResult.Text = string.Format("Result is: {0}", b.ToString());
}
}
}
Step 4: The output for the application when value is null:
Step 5: The output for the application when value is not null