• Home
  • ASP.NET
  • JavaScript
  • SQL
  • WebService
  • OOPs
  • Jquery
  • GridView
  • MVC

Wednesday, February 10, 2016

String Interpolation

 Unknown     9:33 PM     No comments   

This one is a simple but very effective improvement in C# 6 that I love. How many times have you used the String.Format() method like this:
var title = String.Format("{0} ({1})", post.Title, post.Comments.Count);
While these placeholders make it easy to define a template, tracing them with their linked arguments causes a bit of distraction. Here, if you want to visualise the output, you have to look at the first placeholder ({0}), and then look at the first argument (post.Title). Then, you look at the second placeholder, and follow it up with the second argument. Your eyes keep moving from left to right.
C# 6 introduces a beautiful way to write the same code in a more direct way:

1
var title = $"{post.Title} ({post.Comments.Count})";
So, you need to prefix your string with $ and then you can replace placeholders with the actual arguments. Isn’t that cleaner?
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 comments:

Post a Comment

Popular Posts

Pages

  • Home
  • SQL
  • Asp-Net
  • GridView
  • Javascript
  • What are HttpHandlers and HttpModules in ASP.NET?

Blog Archive

  • March 2016 (12)
  • February 2016 (16)

Contact Form

Name

Email *

Message *

Followers

Follow us

  • Facebook
  • Twitter
  • Instagram
  • Pinterest
  • Bloglovin
  • Youtube

Copyright © Code Wrapper | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com | Distributed By Gooyaabi Templates