3 small things in C# code

The below code snippets will give the clear idea about the 3 things which can be used in the C# best practice code while implementation in any project.

1. Null Coalescing Operator (??)

This is the new operator which can be used as the shortcut of ternary operator to check the null value:

Ternary operator (?:):

In the below code, we can see the ternary operator is used to write the checking of null values only in single line.

string empName = (value != null) ? value : string.Empty;

This code describes that if the value is not null then it should return the value and assign it to the string empName. And if the value is null then it should take it as string.Empty.

we can write it using null-coalescing operator (??):

string empName = value ?? string.Empty;

Now we can see the one line code using ternary operator can be written only in lest than 1 line using null-coalescing operator. This code snippet also the same. So we can use it for readability and simplicity of the code.

2. The As Cast

we might have seen the code something like:

if (customer is DeluxCustomer)
var dCust = (DeluxCustomer)customer
// ...

This code is first checking that if the customer is in the DeluxCustomer then get the customer value and box it with the DeluxCustomer type.

This is redundant because we are checking the type twice. Once in the is check and once in the cast.

We can use as operator in place. This will cast the type if the types are compatible, or return null if not:

var dCust = customer as DeluxCustomer;
// ... we can write if condition to check for null

Here the 'as' operator is using and assigning the object directly without boxing so we can avoid double-checking the type.

3. Auto-Properties

This is the new concept to define the properties in C#: we can define the auto-property without much code:

public class Name
public int name { get; set; }
public int name { get; set; }

Now there is no need to declare the private variable and assign the value to the property getter and setter.

Reference: http://pawantechit.blogspot.com/


Author: Siva Prasad26 Mar 2012 Member Level: Gold   Points : 0

These are seems to be small things but improvises a lot in programming. Especially Null Coalescing Operator (??) is good one.

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: