Dotnet courses New features in C# 6.0. Best Dot Net Training
Agenda: New Features of C# 6.0
Dotnet courses New features in C# 6.0. Best Dot Net Training
- String Interpolation
- Null Conditional Operator
- Auto Property Initializer
- Dictionary / Index Initializer
- Expression-bodied function members
- Static Using
- name of Expression
- Exception Filters
- Declaration Expressions
- await in catch and finally block
String interpolation
It’s a feature which can eradicate the use of String. Format method which at times becomes little confusing.
class Person {
public string Name;public int Age;
}
class Program
{
static void Main()
{
Person p = new Person() { Name = “Abcd”, Age =25 };
var s = String.Format(“{0} is {1} year(s) old”, p.Name, p.Age);
Console.WriteLine(s);
var s1 = $”{p.Name} is {p.Age} year(s) old”;
Console.WriteLine(s1);
}
}
Null Conditional Operator (?.) :
If the object invoking the method or accessing the property is null, then the operator results in null expression.
static void Main(string[] args)
{
string s = null;
s = Trucate(s, 2);
Console.WriteLine(s);}
static string Trucate(string s, int len)
{
/*if (s != null)
return s.Substring(0, len); return null;*/
return s?.Substring(0, len);
}
}
Auto-property Initializer
This feature enables you to set the values of properties right at the place where they are declared. In the earlier versions of C# we had to often use default constructors to set default values to the properties in the class.
class Person{
//public Person()
//{
// Name = “John”;
// Age = 25;
//}
public string Name { get; set; } = “John”; public int Age { get; set; } = 25;
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
Console.WriteLine(p.Name + ” “ + p.Age);
}
}
Dictionary / Index initializers
Dictionary / Index initializers allow you to set values to keys through any indexer that the new object has
Dictionary<string, string> capitals = new Dictionary<string, string>(){
[“USA”] = “Washington DC”,
[“England”] = “London”,
[“India”] = “New Delhi”
};
var numbers = new Dictionary<int, string>
{
[7] = “seven”,
[9] = “nine”,
[13] = “thirteen”
};
Expression-bodied function members
Methods, as well as user-defined operators and conversions, can be given an expression body by use of the “lambda arrow”:
class Point {
public int x, y; public Point(int a,int b)
{
x = a; y = b;
}
public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
}
public static Complex operator +(Complex a, Complex b) => a.Add(b); public static implicit operator string(Person p) => p.FirstName + ” ” + p.LastName;
The effect is exactly the same as if the methods had had a block body with a single return statement. For void-returning methods – the arrow syntax still applies, but the expression following the arrow must be a statement expression:
public void Print() => Console.WriteLine(FirstName + ” ” + LastName);
Using static
The feature allows all the accessible static members of a type to be imported, making them available without qualification in subsequent code:
using static System.Math;
using static System.DayOfWeek;class Program
{
static void Main()
{
WriteLine(Sqrt + 4 * 4));
WriteLine(Friday, Monday);
}
}
name of Expressions
Occasionally you need to provide a string that names some program element: when throwing an
ArgumentNullException you want to name the guilty argument; when raising a PropertyChanged event you want to name the property that changed, etc.
Using string literals for this purpose is simple, but error-prone. You may spell it wrong. name of expressions are essentially a fancy kind of string literal where the compiler checks that you have something of the given name, and Visual Studio knows what it refers to so navigation and refactoring will work:
- If the parenthesized expression evaluates to true, the catch block is run, otherwise, the exception keeps going.
- Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.
- It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:
{if (param1 == null)throw new ArgumentNullException(); if (param2 == null)throw new ArgumentNullException();// }
await in catch and finally blocks:
In C# 5 doesn’t allow the await keyword in catch and finally, blocks and developers had to look for work around.
Now in C# 6 figured this issue is resolved and following an example.
{ FileStream fs = new FileStream(“src.txt”, FileMode.Open); try { MemoryStream ms = new MemoryStream(); await fs.CopyToAsync(ms); } catch (IOException) { await fs.FlushAsync(); } finally
{
byte[] buffer = new byte[10];
await fs.WriteAsync(buffer, 0, 10);
if (fs != null)
fs.Close();
}
}