In this post we will see the newly added features in C# 6.0. In C# 6.0 some very cool features has been added like "Auto-property Enhancements", "Primary Constructors", "Expressions as Function Body", "Use of Static", "Exception Filters", "inline declarations", "nameof Expressions", "Null-conditional Operators", "String interpolation", "Await in catch and finally".
Introduction
Here, you will find nine new cool features of C# 6.0:- Auto-property Enhancements
- Parameters on Classes and Structs
- Using Static
- Exception Filters
- Null-conditional Operators
- Index Initializers
- $ sign
- String Interpolation
- nameof Expression
- Await in catch and finally block
Auto-property Enhancements
You can initialize the properties in the same way as you initialize variables, fields.
12345public
class
Employee
{
public
string
FirstName {
get
;
set
; } =
"Pankaj"
;
public
string
LastName {
get
;
set
; } =
"Maurya"
;
}
Parameters on Classes and Structs
You can pass the parameter to the classes/structs in the same way as you do with the methods/functions.
You can also add the logic on parameters as:12345public
class
Employee(
string
firstName,
string
lastName)
{
public
string
FirstName {
get
;
set
; } = firstName;
public
string
LastName {
get
;
set
; } = lastName;
}
123456789public
class
Employee(
string
firstName,
string
lastName)
{
if
(Equals(firstName,
null
))
{
throw
new
ArgumentNullException(
"firstName"
);}
if
(Equals(lastName,
null
))
{
throw
new
ArgumentNullException(
"lastName"
);}
public
string
FirstName {
get
; } = firstName;
public
string
LastName {
get
; } = lastName;
}
Using Static
In C# 6.0, Microsoft announced a new behaviour to our CS compiler that allows us to call all the static methods from the static class without the name of the classes.
Code in C# 5.0
Code in C# 6.0123456789static
void
Main(
string
[] args)
{
Console.WriteLine(
"Enter first number :"
);
int
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(
"Enter second number :"
);
int
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(
"Multiplication : {0}"
, (num1 * num2));
Console.ReadLine();
}
123456789101112131415using
static
System.Console;
using
static
System.Convert;
public
class
UsingStaticTest
{
static
void
Main(
string
[] args)
{
WriteLine(
"Enter first number :"
);
int
num1 = ToInt32(ReadLine());
WriteLine(
"Enter second number :"
);
int
num2 = ToInt32(ReadLine());
WriteLine(
"Multiplication : {0}"
, (num1 * num2));
ReadLine();
}
}
Exception Filters
With this new feature, you can add conditional logic to catch block that decide which catch block will execute based on condition.
123456789101112try
{
throw
new
Exception(
"Pankaj"
);
}
catch
(Exception ex)
if
(ex.Message ==
"Pankaj"
)
{
// this will execute because exception message matches.
}
catch
(Exception ex)
if
(ex.Message ==
"Maurya"
)
{
// this will not execute because exception message does not match
}
Null-conditional Operators
The Null-Conditional operator is a new concept in C# 6.0 that automatically checks with null references. In previous version C# 5.0, if we are accessing any property of a class, then first we check the object of class with null and if not null, then reading the property but in C# 6.0, you can do the same with "?" operator.
Code in C# 5.0
Code in C# 6.01234567891011121314151617181920212223242526272829303132namespace
ConditionalTest
{
class
Program
{
static
void
Main()
{
Employee emp =
new
Employee(){
FullName =
"Pankaj Maurya"
,
EmpAddress =
new
Address()
{
ResidenceAddress =
"New Ashok Nagar"
,
OfficeAddress =
"Udyog Vihar Pahse 2"
}
}
if
(emp!=
null
&& emp.EmpAddress!=
null
)
{
WriteLine((emp.FullName) +
" "
+ (emp.EmpAddress.ResidenceAddress??
"No Address"
));
}
ReadLine();
}
}
class
Employee
{
public
string
FullName {
get
;
set
; }
public
Address EmpAddress {
get
;
set
; }
}
class
Address
{
public
string
ResidenceAddress {
get
;
set
; }
public
string
OfficeAddress {
get
;
set
; }
}
}
1234567891011121314151617181920212223242526272829namespace
ConditionalTest
{
class
Program
{
static
void
Main()
{
Employee emp =
new
Employee(){
FullName =
"Pankaj Maurya"
,
EmpAddress =
new
Address()
{
HomeAddress =
"New Ashok Nagar"
,
OfficeAddress =
"Udyog Vihar Pahse 2"
}
}
WriteLine((emp?.FullName) +
" "
+ (emp?.EmpAddress?.ResidenceAddress??
"No Address"
));
ReadLine();
}
}
class
Employee
{
public
string
FullName {
get
;
set
; }
public
Address EmpAddress {
get
;
set
; }
}
class
Address
{
public
string
ResidenceAddress {
get
;
set
; }
public
string
OfficeAddress {
get
;
set
; }
}
}
Index Initializers
C# 6.0 introduces new syntax to initialize index based collections.
Code in C# 5.0
Code in C# 6.0123456var persons =
new
Dictionary<
int
string
=
""
> {
{ 3,
"Pankaj"
},
{ 4,
"Manish"
},
{ 6,
"Anand"
}
};
</
int
>
123456var persons =
new
Dictionary<
int
string
=
""
> {
[3] =
"Pankaj"
,
[4] =
"Manish"
,
[6] =
"Anand"
};
</
int
>
$ Sign
C# introduces new to initialize and access index objects.
1234567891011121314var persons =
new
Dictionary<
string
string
=
""
>()
{
// using inside the intializer
$first =
"Pankaj"
};
//Assign value to member
//in C# 5.0
persons[
"first"
] =
"Pankaj"
;
// in C# 6.0
persons.$first =
"Pankaj"
;
</
string
>
String Interpolation
Before C# 6.0, if we need to format strings, then we used String.Format() method, which is taking an input string filling placeholders with indexes and then providing an array of values which is plotted in the string with their respective indexes. Let us suppose an Employee class has two properties, FirstName and LastName and we have to put the FullName then generally we are using it like:
In C# 6.0, a new feature String Interpolation (use $ to format string) is added which provides the formatting of string with the source of parameter value itself.1string
FullName = String.Format(
"{0} {1}"
,FirstName,LastName);
1string
FullName = $
"{FirstName} {LastName}"
;
nameof Expression
Before C# 6.0, when we need to use a property, function or a data member name into a message as a string, so we need to use the name as hard-coded in “name” in the string and in the future if my property or method's name changed, so we have to change all the messages in every form or every page.
To resolve this issue, C# 6.0 introduces nameof as new keyword which will return string literal of the name of property or a method.
Code in C# 5.0
Code in C# 6.012345678910111213141516171819namespace
NameOfTest
{
class
Program
{
static
void
Main(
string
[] args)
{
Employee emp =
new
Employee();
WriteLine(
"{0} : {1}"
,
"EmpCode"
, emp.EmpCode);
WriteLine(
"{0} : {1}"
,
"EmpName"
, emp.EmpName);
ReadLine();
}
}
class
Employee
{
public
int
EmpCode{
get
;
set
; } = 101;
public
string
EmpName {
get
;
set
; } =
"Pankaj"
;
}
}
12345678910111213141516171819namespace
NameOfTest
{
class
Program
{
static
void
Main(
string
[] args)
{
Employee emp =
new
Employee();
WriteLine(
"{0} : {1}"
, nameof(Employee.EmpCode), emp.EmpCode);
WriteLine(
"{0} : {1}"
, nameof(Employee.EmpName), emp.EmpName);
ReadLine();
}
}
class
Employee
{
public
int
EmpCode{
get
;
set
; } = 101;
public
string
EmpName {
get
;
set
; } =
"Pankaj"
;
}
}
Await in Catch and Finally Block
Let's suppose a situation where we need to call an async method and there is a try and a catch{} block, so when the exception occurs, it is thrown in the catch{} bock. We need to write log information into a file or send a service call to send exception details to the server so call the asynchronous method, this is only possible in C# 6.0 by using await in catch{} block.
123456789101112131415161718192021222324252627282930namespace
AwaitCatchTest
{
public
class
CustomMath
{
public
async
void
DivisionWrapper(
int
num1,
int
num2)
{
try
{
int
res = num1/ num2;
WriteLine(
"Division : {0}"
, res);
}
catch
(Exception ex)
{
await asyncMethodForCatch();
}
finally
{
await asyncMethodForFinally();
}
}
private
async Task asyncMethodForCatch()
{
WriteLine(
"Method from async Catch !!"
);
}
private
async Task asyncMethodForFinally()
{
WriteLine(
"Method from async finally !!"
);
}
}
}
No comments:
Post a Comment