C#6.0 新特性

关注一下其他语言的发展。其中5Java中是有的,import static1~4都挺有用的。

 

New featuresin C# 6.0

We can discussabout each of the new feature but first list of few features in C# 6.0

1.      Auto Property Initializer

2.      Primary Consturctors

3.      Dictionary Initializer

4.      Declaration Expressions

5.      Static Using

6.      await inside catch block

7.      Exception Filters

8.      Conditional Access Operator to check NULL Values

1. Auto Property initialzier

Before

The only way toinitialize an Auto Property is to implement an explicit constructor and setproperty values inside it.

public class AutoPropertyBeforeCsharp6

{

   private string _postTitle = string.Empty;

   public AutoPropertyBeforeCsharp6()

   {

        //assign initialvalues

       PostID = 1;

       PostName = "Post 1";

   }

 

   public long PostID { get; set; }

 

   public string PostName { get; set; }

 

   public string PostTitle

   {

        get { return _postTitle; }

        protected set

        {

           _postTitle = value;

        }

   }

}

After

In C# 6 autoimplemented property with initial value can be initialized without having to write the constructor. We can simplify the above exampleto the following

public class AutoPropertyInCsharp6

{

   public long PostID { get;  } = 1;

 

   public string PostName { get; } = "Post 1";

 

   public string PostTitle { get; protected set; } = string.Empty;

}

2. PrimaryConstructors

We mainly useconstructor to initialize the values inside it.(Acceptparameter values and assign those parameters to instance properties).

Before

public class PrimaryConstructorsBeforeCSharp6

{

   public PrimaryConstructorsBeforeCSharp6(long postId, string postName, string postTitle)

   {

       PostID = postId;

       PostName = postName;

       PostTitle = postTitle;

   }

 

   public long PostID { get; set; }

   public string PostName { get; set; }

   public string PostTitle { get; set; }

}

After

public class PrimaryConstructorsInCSharp6(long postId, string postName, string postTitle)

{       

   public long PostID { get;  } = postId;

   public string PostName { get; } = postName;

   public string PostTitle { get;  } = postTitle;

}

In C# 6, primaryconstructor gives us a shortcut syntax for defining constructor withparameters. Only one primary constructor per class is allowed.

If you closelyat the above example we moved the parameters initialization beside the classname.

You may get thefollowing error “Feature ‘primary constructor’ is only available in‘experimental’ language version.” To solve this we need to editthe SolutionName.csproj file to get ridof this error. What you have to do is we need to add additional settingafter WarningTag

<LangVersion>experimental</LangVersion>


Feature ‘primary constructor’ is only available in ‘experimental’ languageversion

3. Dictionary Initializer

Before

The old waywriting an dictionary initializer is as follows

public class DictionaryInitializerBeforeCSharp6

{

   public Dictionary<string, string> _users = new Dictionary<string, string>()

   {

        {"users", "Venkat BagguBlog" },

        {"Features", "Whats new inC# 6" }

   };

}

After

We can definedictionary initializer like an array using square brackets

public class DictionaryInitializerInCSharp6

{

   public Dictionary<string, string> _users { get; } = new Dictionary<string, string>()

   {

        ["users"]  = "Venkat Baggu Blog",

        ["Features"] =  "Whats new in C# 6"

   };

}

4. Declaration Expressions

Before

public class DeclarationExpressionsBeforeCShapr6()

{

   public static int CheckUserExist(string userId)

   {

        //Example 1

        int id;

        if(!int.TryParse(userId, out id))

        {

           return id;

        }

        return id;

   }

 

   public static string GetUserRole(long userId)

   {

        ////Example 2

        var user =_userRepository.Users.FindById(x => x.UserID == userId);

        if (user!=null)

        {

           // work with address ...

 

           return user.City;

        }

   }

}

After

In C# 6 you candeclare an local variable in middle of the expression.With declaration expressions we can also declare variables inside if statementsand various loop statements

public class DeclarationExpressionsInCShapr6()

{

   public static int CheckUserExist(string userId)

   {

        if(!int.TryParse(userId, out var id))

        {

           return id;

        }

        return 0;

   }

 

   public static string GetUserRole(long userId)

   {

        ////Example 2

        if ((var user =_userRepository.Users.FindById(x => x.UserID == userId) != null)

        {

           // work with address ...

 

           return user.City;

        }

   }

}

5. Using Statics

Before

To you staticmembers you don’t need an instance of object to invoke a method. You use syntaxas follows

TypeName.MethodName

public class StaticUsingBeforeCSharp6

{

   public void TestMethod()

   {

       Console.WriteLine("Static Using Before C# 6");

   }

}

After

In C# 6 you havethe ability to use the Static Members without using the type name. You can import the static classes in thenamespaces.

If you look atthe below example we moved the Static Console class to the namespace

using System.Console;

namespace newfeatureincsharp6

{

   public class StaticUsingInCSharp6

   {

        public void TestMethod()

        {

           WriteLine("Static Using Before C# 6");

        }

   }

}

6. await inside catch block

Before C#6 await keyword is not available inside the catch and finallyblock. In C# 6 we can finally use the await keyword inside catch and finallyblocks.

try

{               

         //Do something

}

catch (Exception)

{

         await Logger.Error("exceptionlogging")

}

7. Exception Filters

Exceptionfilters allow you a feature to check an if conditionbefore the catch block excutes.

Consider anexample that an exception occurred now we want to check if the InnerException null then it will executes catch block

//Example 1

try

{

   //Some code

}

catch (Exception ex) if (ex.InnerException == null)

{

   //Do work

 

}

 

//Before C# 6 we write the above code as follows

 

//Example 1

try

{

   //Some code

}

catch (Exception ex)

{

   if(ex.InnerException != null)

   {

        //Do work;

   }

}

8. Conditional Access Operator to check NULL Values ?.

Consider anexample that we want to retrieve an UserRanking based on the UserIDonly if UserID is not null.

Before

var userRank = "No Rank";

if(UserID != null)

{

   userRank = Rank;

}

 

//or

 

var userRank = UserID != null ? Rank : "No Rank"

After

var userRank = UserID?.Rank ?? "No Rank";

The post Newfeatures in C# 6.0 appeared first on Venkat Baggu Blog

.

 

 

原文地址:https://www.cnblogs.com/xiaomaohai/p/6157646.html