Skip to main content

New in C#6

1. $ sign
The purpose for it is to simplify string based indexing and that is all. its not some thing like current dynamic features of C# since it internally uses regular indexing functionality. to understand lets consider following
example:
var col = new Dictionary()
{
// using inside the intializer
$first = "Hassan"
};
//Assign value to member
//the old way:
col["first"] = "Hassan";
// the new way
col.$first = "Hassan";

2. Exception filters:
Exception filters are already supported in VB compiler but now they are coming into C#. exception filters lets you specify a condition for a catch block. the catch block gets executed only if the condition is satisfied, this one is my favorite feature, so let's look at an example:
Collapse | Copy Code
try
{
throw new Exception("Me");
}
catch (Exception ex) if (ex.Message == "You")
{
// this one will not execute.
}
catch (Exception ex) if (ex.Message == "Me")
{
// this one will execute
}

3. await in catch and finally block:
As far as I know, no one know why in C# 5 using await keyword in catch and finally block was not available, any way its now possible to use though. this is great because often we want to perform I/O operation in order to log the exception reason in catch block or such things in finally block and they Need asynchrony.
Collapse | Copy Code
try
{
DoSomething();
}
catch (Exception)
{
await LogService.LogAsync(ex);
}

4. Declaration expressions
This feature simply allows you to declare local variable in the middle of an expression. It is as simple as that but really destroys a pain. I have been doing a lot of asp.net web form projects in the past and this was my every day code:
Collapse | Copy Code
long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }
which can be improved to this:
Collapse | Copy Code
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }

The scoping rules for this kind of declaration is same as general scoping rules in C#.

5. using Static
This feature allows you to specify a particular type in a using statement after that all static members of that type will be accessible is subsequent code.
using System.Console;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
//Use writeLine method of Console class
//Without specifying the class name
WriteLine("Hellow World");
}
}
}

6. Auto property initializer:
With C# 6 initialize auto properties just like a field at declaration place. The only thing to notice here is that this initialization dose not cause the setter function to be invoked internally. the value of backing field is set directly. so here is an example:
Collapse | Copy Code
public class Person
{
// You can use this feature on both
//getter only and setter / getter only properties

public string FirstName { get; set; } = "Hassan";
public string LastName { get; } = "Hashemi";

}
7. Primary Constructor:
Woohooo, primary constructors will help destroy the pain of capturing values of constructor parameters to fields in the class for further operations. This is really useful. The main purpose for it is using constructor parameters for initialization. When declaring a primary constructor all other constructors must call the primary constructor using :this().
here is an example finally:
Collapse | Copy Code
//this is the primary constructor:
class Person(string firstName, string lastName)
{
public string FirstName { get; set; } = firstName;
public string LastName { get; } = lastName;
}

notice that declaration of primary constructor is at the top of the class.

8- Dictionary Initializer:
some people believed that the old way of initiailzing dictionaries was dirty so the C# team dicided to make it cleaner, thanks to them. here is an example of the old way and new way:

Collapse | Copy Code
// the old way of initializing a dictionary
Dictionary oldWay = new Dictionary()
{
{ "Afghanistan", "Kabul" },
{ "United States", "Washington" },
{ "Some Country", "Some Capital city" }
};

// new way of initializing a dictionary
Dictionary newWay = new Dictionary()
{
// Look at this!
["Afghanistan"] = "Kabul",
["Iran"] = "Tehran",
["India"] = "Delhi"
};

Comments

Popular posts from this blog

NHibernate QueryOver Class And Projection....

Introduction The ICriteria API is NHibernate's implementation of Query Object . NHibernate 3.0 introduces the QueryOver api, which combines the use of Extension Methods and Lambda Expressions (both new in .Net 3.5) to provide a statically typesafe wrapper round the ICriteria API. QueryOver uses Lambda Expressions to provide some extra syntax to remove the 'magic strings' from your ICriteria queries. So, for example: .Add(Expression.Eq("Name", "Smith")) becomes: .Where<Person>(p => p.Name == "Smith") With this kind of syntax there are no 'magic strings', and refactoring tools like 'Find All References', and 'Refactor->Rename' work perfectly. Note: QueryOver is intended to remove the references to 'magic strings' from the ICriteria API while maintaining it's opaqueness. It is not a LINQ provider; NHibernate 3.0 has a built-in

Passing Data from View to Controller Using Ajax Example Jquery

Jquery       $ ( '#btnSaveComments' ). click ( function () { var comments = $ ( '#txtComments' ). val (); var selectedId = $ ( '#hdnSelectedId' ). val (); $ . ajax ({ url : '<%: Url.Action("SaveComments")%>' , data : { 'id' : selectedId , 'comments' : comments }, type : "post" , cache : false , success : function ( savingStatus ) { $ ( "#hdnOrigComments" ). val ( $ ( '#txtComments' ). val ()); $ ( '#lblCommentsNotification' ). text ( savingStatus ); }, error : function ( xhr , ajaxOptions , thrownError ) { $ ( '#lblCommentsNotification' ). text ( "Error encountered while saving the comments." ); } }); });     Controller    [ HttpPost ] public ActionResult SaveComments ( int id , string com

The Core Concepts of Angular -- Jithin CJ

I started to learn angular from 2016, I was very curious about the celibacy of this super hero. From my initial understanding is like, the power of angular is only limited on " html decoration "  But this JavaScript framework has the potential to re-define conventional html-css patterns . Modern browsers support for things like modules, classes, lambdas, generators, etc. These features fundamentally transform the JavaScript programming experience. But big changes aren't constrained merely to JavaScript. Web Components are on the horizon. The term Web Components usually refers to a collection of four related W3C specifications: Custom Elements - Enables the extension of HTML through custom tags.  HTML Imports - Enables packaging of various resources (HTML, CSS, JS, etc.).  Template Element - Enables the inclusion of inert HTML in a document.  Shadow DOM - Enables encapsulation of DOM and CSS.  Developers can create fully encapsulated (Shadow DOM) declar