Blog Archives

C# 6.0 – Elvis operator and other improvements


Microsoft has released yet another version of .Net framework (4.6) and C# (6.0). In this post I am highlighting few improvements released as part of C# 6.0 which will largely benefit day to day development activities of a C# developer.

Elvis operator or formally called null conditional operator (?.) makes the null check simple. In a highly hierarchical object structure this operator reduces the length of code required to check for null and proceed further.

public class Sale
public Order orderItem { get; set; } = new Order();
public class Order
public int orderId { get; } = 101;

To read the value of orderId from main() class, null checks are required on objects of two of its hierarchical structure.

Sale sale = new Sale();

if(sale != null && sale.orderItem !=null && sale.orderItem.orderId > 0)
Console.WriteLine(string.Format("In older C#, value is {0}", sale.orderItem.orderId));

if (sale?.orderItem?.orderId >0)
Console.WriteLine($"In 6.0 C#, value is {sale.orderItem.orderId}");

Elvis operator makes this simple by evaluating the above expression left to right. The expression sale?.orderItem?.orderId >0 evaluates to orderItem if the left operand sale is non-null; otherwise, it evaluates to null.

In the above class definition, you will observe the way I have initialized the properties. I have directly initialized orderItem next to the property definition and it’s called auto-property initializer. Also you will notice orderItem has only get and no setter, this feature is called get-only auto property.

Also in the above code block you will notice, first I used string.Format to format the string and latter a special and simplified template to do the same. This is again a new feature in C# 6.0 called Interpolated Strings. An interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions’ results.


Visual Studio Online


Wow!! This the word I exclaimed when I first saw Visual Studio Online. This is combination of collaboration, planning, version control tools and over cloud. Exciting??!!   Actually this is not something new, Microsoft has renamed their existing Team Foundation Service as Visual Studio One.

As soon as I installed Visual Studio 2013, it asked me to create profile. That’s it!!! I am now ready with all above said combination of tools to start.


You can choose among TFS and Git as your version control system and this gets integrated with your Visual Studio IDE. So as you create the project, you can start collaborating with your team members. Also there are various out of box agile/scrum templates to manage your epic, stories and iterations. In addition to these, VSO (Visual Studio Online) has quality related tools integrated. You can do code reviews, build, test plans, test case execution etc.

Advanced VSO even provide lighter version of Visual Studio to edit code, automated builds, load tests, etc. With Visual Studio Online, Microsoft is offering broad range of tools and services that support the different kinds of development code named “Monaco” specifically designed for building and maintaining Windows Azure Websites.

Visual Studio 2012 – Paste XML as Classes

images (1)

Here we have a new version of Microsoft Visual Studio, Visual Studio 2012.

This new version is coming out at the time of diversification of computing technology and platform. So this new version is loaded with new capabilities for Windows 8, the web, SharePoint, mobile, and cloud development.

This new version has brought a lot of new and interesting features. Out of which today I was more exited with feature “Paste XML as Classes”.

Paste XML as Classes

Say you have a well formed XML file and need to deserialize it to a fully qualified .Net type objects. Building this manually is a very dull and monotonous job. Visual Studio 2012 has a new feature “Paste XML as Classes”.

Below is one sample well-formed XML.

Copy the XML content and open a new class file. From the menu select select Edit | Paste Special | Paste XML as Classes as shown below.

Visual Studio will automatically generate the code as shown below.

Pass JSON object from Javascript code to MVC controller

I made a lot of search to know how to pass JSON object from client code to MVC control. But I could not find any proper example or guide. So finally I made some research and I found that by serializing the JSON object using json.js, it is possible to send serialized data to MVC control from client side.

Let me elaborate these steps:

1st it requires json.js included in your project.

In Step 1 I created an array of literals containing object literals. This is the client code with three fields’ id, name and email which we want to send to server. Step by step explanation on this structure could be found here.

In Step 2 we are serializing this object into a string with help of json library method $.toJSON().

In Step 3 we are sending this serialized data to MVC control action via AJAX post.

Step 1:
function SaveData() {
var dobj = [{ id: 1, name: 'ABCD', email: '' },
{ id: 2, name: 'EFGH', email: '' },
{ id: 3, name: 'IJKL', email: '' },
{ id: 4, name: 'MNOP', email: ''}];

Step 2:
var jlst = $.toJSON(dobj);

Step 3:
$.post("/DistributionList/SaveMyData/", { jsonData: jlst },
function(data, textStatus) {
if (textStatus != "success") {
result = "false";

With this our client side task is complete.

Next is to consume this data at the server side, i.e. at MVC control.

At server control side we have an action which accepts string data. Serialized json object will be routed here. To deserialize this data you require an object of JavaScriptSerializer which is available in System.Web.Script.Serialization library.

Create a model class with excat number of fileds to hold the deserialized data.

public class PersonData
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }

In the below code we have created an object of List of type Person to hold the multiple person information. With the help of JavaScriptSerializer object we are able to deserialize the JSON object.

public ActionResult SaveMyData(string jsonData)
bool result = true;
List<PersonData> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData= jss.Deserialize<List<PersonData>>(jsonData);


return Content(result.ToString());

Conclusion: Hope this post would be helpful those who are find difficult to pass JSON data from client side to any server side control. If you find anything wrong or better way to do the thing please let me know.


Handle optional parameterized method of VB.Net or COM in C#

Although optional parameters are actually a very good feature, C# does not support them. Now what about assemblies created in VB.Net with methods having optional parameter, how to call them from C# code? Since C# doesn’t support the concept of optional parameter, if you don’t supply required parameters while making a call to such methods, compiler will throw an error.

So how to handle this? There are many ways to address this issue:
1. If the required parameter is of any reference type such as String then you can use
System.Reflection.Missing.Value or  System.Text.Missing
While making call to such methods pass the above value as optional parameter.
2. Create a Wrapper class in VB.Net and overload the method with different available options. This assembly could be referenced by the original C# application.

Now the upcoming version of C# 4.0 is going to have a feature of Optional Parameter
C# 4.0 can both declare and consume optional parameters. Here’s a sample of a very simple method that declares a parameter as optional:

public static class OptionalDemoLib
public static void SayHello(string s = "Hello World!")

This means you can either call Do with one argument or without an argument, in which case the default value is used:

public static class OptionalDemo
public static void Main()
OptionalDemoLib.SayHello("Hello India!");