Translate to your language...

26 March 2011

3 small things in C# code

1. Null Coalescing Operator (??)

A new operator can be used which can be shortcut of ternary operator to check the null value:

Ternary operator (?:):

string empName = (value != null) ? value : string.Empty;
we can write it using null-coalescing operator (??):
string empName = value ?? string.Empty;

2. The As Cast
we might have seen the code something like:
if (customer is DeluxCustomer)
{
var dCust = (DeluxCustomer)customer
// ...
}
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
}
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 Employee
{
public int ID { get; set; }
public string name { get; set; }
}

1 comment:

  1. hi pawan,

    you are declaring the name as two times it will give an compile time error......

    ReplyDelete

Sr .Net Consultant | MCP Certified | Microsoft Technologies(.Net with Sql Server, MVC, AngularJS

My photo
Kuala Lumpur, Kuala Lumpur, Malaysia
Overall 17.0+ years of experience in software industry as a Programmer/Developer/Architect with Web & Windows application development and Maintenance, including analysis, design, coding, testing and documentation. • Proficient in Microsoft Technologies i.e. Visual Studio with .Net Framework. • Excellent analytical, problem solving, communication, interpersonal skills with the ability to handle multiple tasks or projects working independently or in a team. • Consistent attention to detail with an ability to analyze and interpret the implication of decisions to minimize bugs and create user-friendly applications. • Experience of Collaborating with Clients and Team Members. Ability to convey Technical Information at all levels. • Ability to work with team/management to ensure successful execution of project management tasks including scheduling, scope management, outside dependency coordination and priorities resolution. • Experience in working with global clients like UK, USA, Europe, Australia etc. and teams located remotely (e.g. Sydney, Australia, USA, and Sweden). • Worked with the Swedish client ManpowerGroup at onsite client location Stockholm, Sweden.