ASP.NET Core MVC 2.0 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Feature one—auto initializer for properties:

Before C# 6, we should initialize a property with a value in the class constructor. There is no point in time before the class constructor, so we should use it. Thanks to C# 6 syntax, we can now initialize a property with a value right on the declaration line. No need to use constructor anymore:

    • Before:
public class Person
{
Public class Name {get;set;}
Public Person(){
Name = "Stephane";
}
}
    • Now:
Public string Name {get;set;} = "Stephane";
  1. Feature two—auto initializer for static properties:

Auto initializers can be applied to static properties, as well:

    • Before:
Public static string Name {get;set;}
    • Now:
Public static string Name {get;set;} = "Stephane";
  1. Feature three—read-only properties:

Auto initializers can even be applied to read-only properties:

    • Before:
public List SocialNetworks { get; }
    • Now:
public List SocialNetworks { get; } =
new List { "Twitter", "Facebook", "Instagram" };
    • Before:
Dictionary<string, User> Users = new Dictionary<string, User>()
{
{ "root", new User("root") },
{ "baseUser", new User("baseUser")}
};
    • Now:
Dictionary<string, User> Users = new Dictionary<string, User>()
{
["root"] = new User("root"),
["baseUser"] = new User("baseUser")
};
  1. Feature four—expression-bodied members:

Simple functions (functions with just a return statement) can now be written inline:

    • Before:
public double GetVAT(int someValue)
{
return someValue * 1.2;
}
    • Now:
public double GetVAT(int someValue) => someValue * 1.2;
private DateTime timestamp;
    • Before:
public DateTime TimeStampCreated
{
get
{
return timestamp;
}
}
    • Now:
public DateTime TimeStampCreated => timestamp;
public static string ReadFile(string fileName) =>
Disposable.Using(
() => System.IO.File.OpenText(fileName),
r => r.ReadToEnd());
The previous piece of code highlights a potential problem that already exists in CSharp, since lambda expressions exist.

It is easy to make fun when writing lambda expressions by creating concise code. It is also easy to write unreadable code, especially for those who will have to use this code. Another problem is that this code is hard to debug.
  1. Feature five—interpolated strings:

We can reference variables by their names directly in the code by using the dollar sign just before the string used to include the variable:

var name = "Stephane";
string.Format($"My name is {name}");
  1. Feature six—null-conditional operators:

To return a null value, we can use a new syntax that allows us to not declare a null variable before returning it:

    • Before:
var username = (User != null) ? User.Name : string.empty;
    • Now:
var username = User?.Name;