String Interpolation and Expression-bodied methods in C# 6.0

We, all C# developers are very much familiar with string.Format(); in C# where we used to

string a = "sample text";
string.Format("This is a {0}",a);

that was awesome but when it comes to use the same methods with more args, it gives a headache and even its sometimes become harder to read the code. Sometimes I personally think why again and again use string.Format();. Now with the new C# Microsoft has provided me an answer that is, String Interpolation. With String interpolation you can just use something like

int a, b = 10;
Console.WriteLine("The value is A is \{a} while B is \{b}");

and even you can depricate that Console also as C# has the feature to using static classes as I said earlier in a blog post.

The next thing I wanted to tell here is Expression bodies methods and properties in C# 6.0, they are just methods, where body contains just a single return statement, for example the like the below.

public override string ToString()
   //consider a has been defined
   return "\{a}";

and think about how to write this method very quickly to boost the developer efficiency, there is were the expression bodied methods helps. Like Lambda expressions, this expression bodied methods helps to implement a methods with lambda arrow. A good example can be

public override string ToString() => "\{a}";

thats all boom…!!
And we can use this for properties as well, instead of using like below

public int AddedNumbers
   get {return a+b;}

we can just use

public int AddedNumbers => a+b;

These are just cool isn’t they.
Happy coding and I will catch you soon with another post guys. Have a blessed stay.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s