Here I am discussing about the new feature called “null-conditional operators” introduced in C# 6.0 (VS 2015 and .Net 4.6).
First we can see the old way,
InvoiceDetails = Invoice != null ? Invoice.InvoiceDetails : null;
If(Invoice != null && Invoice.InvoiceDetails != null)
{
Amount = Invoice.InvoiceDetails.Amount.;
}
else
{
Amount = 0;
}
Or
Amount = Invoice != null ? (Invoice.InvoiceDetails != null ? Invoice.InvoiceDetails.Amount : 0) : 0;
In the above code used null conditional operator, nested if statements etc. In C# 6.0 provides the new way to check for Null. We can use Null-conditional operator (“?.”) for reduce number of lines of codes.
InvoiceDetails = Invoice?.InvoiceDetails;
If all of the conditions are met, this will return the actual value; otherwise, it will return null. It checks the InvoiceDetails object and returns a value if Invoice is not equal to null; else, it returns null.
Amount = Invoice?.InvoiceDetails?.Amount;
In this case either Invoice or Invoice details is null then returns null value.
Amount = Invoice?.InvoiceDetails?.Amount ?? 0;
Here we can return if Amount is null then 0 using "??" operator.
Advantages
By lowering the number of lines of code, developers may work more efficiently. Additionally, by keeping the code clean, it may help lower the potential number of problems in the code.
First we can see the old way,
InvoiceDetails = Invoice != null ? Invoice.InvoiceDetails : null;
If(Invoice != null && Invoice.InvoiceDetails != null)
{
Amount = Invoice.InvoiceDetails.Amount.;
}
else
{
Amount = 0;
}
Or
Amount = Invoice != null ? (Invoice.InvoiceDetails != null ? Invoice.InvoiceDetails.Amount : 0) : 0;
In the above code used null conditional operator, nested if statements etc. In C# 6.0 provides the new way to check for Null. We can use Null-conditional operator (“?.”) for reduce number of lines of codes.
InvoiceDetails = Invoice?.InvoiceDetails;
If all of the conditions are met, this will return the actual value; otherwise, it will return null. It checks the InvoiceDetails object and returns a value if Invoice is not equal to null; else, it returns null.
Amount = Invoice?.InvoiceDetails?.Amount;
In this case either Invoice or Invoice details is null then returns null value.
Amount = Invoice?.InvoiceDetails?.Amount ?? 0;
Here we can return if Amount is null then 0 using "??" operator.
Advantages
By lowering the number of lines of code, developers may work more efficiently. Additionally, by keeping the code clean, it may help lower the potential number of problems in the code.
Comments
Post a Comment