Several new syntactical improvements with C# 6.0 were introduced and these are as follows1. Using Static directive for namespaces
2. Auto property Initializer
3. Index Initializer
4. String Interpolation
5. Expression Bodied Members
6. Getter Only Auto Properties
7. Exception Filters
8. Null Conditional Operators
9. nameOf Expression
10. Await in Catch/Finally Block
1. Using Static directive for namespaces
Now, we can define the namespace via using static to access
the property or the method of the
static class. We
need to add
only using static
directive before the
namespace of the
class.
Before C# 6.0,
we use ReadLine(),
WriteLine() methods of
the Console class
using defining
System.Console.ReadLine() and System.Console.WriteLine()
explicitly.
So in C#
6.0, we use
it like below
while declaring the
namespace. It is
because, System.Console is a static class.
using static System.Console;
When we define the
System.Console class with static in using section, we can access all the
properties and methods
of the static
class System.Console without
writing the Console class name again and again.
After using “Using
static”, we can
write our code
simple as “WriteLine(“XYZ”);” rather
than“Console.WriteLine(“XYZ”);”
C# 6.0 provides the flexibility to use static class without
the reference of the class every time.
We only need to define it in using static statement and we
can access it.
Before C# 6.0
Console.WriteLine("Sample example for WriteLine()
method before C# 6.0");
Console.ReadLine();
In C# 6.0
using System;
using static System.Console;
static void Main(string[] args)
{
WriteLine("This is a demo for C# 6.0 New Features: Using
Static");
ReadLine();
}
We can also apply using static directive to our own custom
static classes to access their static
members.
static class MyClass
{
public static void
Hello()
{
WriteLine("This is Main Method");
}
}
using static MyApplication.MyClass;
Auto Property Initializer
To access the internal members of a class, we use the
properties. Properties have their getter and setter methods.
Before C# 6.0, we could not directly
define the value of the property.
To do this, we basically used the local member variables but C#
6.0 provides the flexibility to initialize the value.
With C# 6.0, we can directly assign the value of the
property at the time of defining the new property.
Before C# 6.0
public class Employee
{
public Guid
EmployeeId { get; set; }
public string
FirstName { get; set; }
public string
LastName { get; set; }
public string
FullName { get; set; }
public
Employee()
{
//Before C#
6.0, Initialize the values in Constructor
EmployeeId
= Guid.NewGuid();
FirstName
= "Mukesh";
LastName =
"Kumar";
FullName =
string.Format("{0} {1}", FirstName, LastName);
}
}
static void Main(string[] args)
{
Employee
emp = new Employee();
Console.WriteLine("Employee Id is " + emp.EmployeeId);
Console.WriteLine("Employee Full Name is " + emp.FullName);
Console.ReadLine();
}
In C# 6.0
C# 6.0 is very smooth and we don't need to worry about how
and where we will initialize the value of the property. You can directly assign the value of
the property after = sign. It will not give you any type of exception and run smoothly.
In the example given below, we can see that EmployeeId is
generating new GUID. It is clearly visible that FirstName and LastName are initialized with
their values.
public class Employee
{
//In C# 6.0,
Initialize the values directly to properties
public Guid
EmployeeId { get; set; } = Guid.NewGuid();
public string
FirstName { get; set; } = "Mukesh";
public string
LastName { get; set; } = "Kumar";
public string
FullName { get { return string.Format("{0} {1}", FirstName, LastName);
} }
}
static void Main(string[] args)
{
Employee
emp = new Employee();
WriteLine("Employee Id is " + emp.EmployeeId);
WriteLine("Employee Full Name is " + emp.FullName);
ReadLine();
}
Index Initializer
C# 6.0 provides the new way to initialize the collection. We
can create index based collections like dictionaries, hash tables etc. As we know that
dictionary is the key-value pair and we need to assign the values for their corresponding keys.
We have
some different way to create thekey/value pair before c# 6.0.
See the following example how we use the key\value pair for
a dictionary object in C# before C# 6.0.
static void Main(string[] args)
{
Dictionary<int, string>
myDictionary = new Dictionary<int, string>() {
{1,
"Mukesh Kumar"},
{2,
"Rahul Rathor"},
{3,
"Yaduveer Saini"},
{4,
"Banke Chamber"}
};
foreach (var item in myDictionary)
{
Console.WriteLine("The " + item.Key + " Number Employee
is " +
item.Value + "\n");
}
Console.ReadLine();
}
But with C# 6.0, we logically define that the value for
index 1 is "Mukesh Kumar" and so on.
You can see the following example which clears your all doubts.
using static System.Console;
namespace CSharp6FeaturesDemo
{
public class
Program
{
static void Main(string[] args)
{
Dictionary<int, string> myDictionary = new Dictionary<int,
string>()
{
[1] =
"Mukesh Kumar",
[2] =
"Rahul Rathor",
[3] =
"Yaduveer Saini",
[4] =
"Banke Chamber"
};
foreach
(var item in myDictionary)
{
WriteLine("The " + item.Key + " Number Employee is "
+ item.Value + "\n");
}
ReadLine();
}
}
String Interpolation
For string concatenation, we generally use String.Format
where we pass the array of the index and then pass the parameters value for it. It is sometimes
very confusing when we are working with multiple parameters value with different index of
position.
Following is the simple example of getting the full name to
use first name and last name.
Here we are using
the String.Format and
after that we
need to specify
the index array
for the parameters value.
Before C# 6.0
static void Main(string[] args)
{
string
firstName = "Mukesh";
string
lastName = "Kumar";
Console.WriteLine("The Full Name of Employee " +
string.Format("{0}{1}",
firstName, lastName));
Console.ReadLine();
}
C# 6.0 has introduced a very great feature where we don't
need to pass the array index, but we can direct pass our variable
but be sure we are using the $
sign before to start.
In C# 6.0
static void Main(string[] args)
{
string
firstName = "Mukesh";
string
lastName = "Kumar";
WriteLine($"The Full Name of Employee {firstName}
{lastName}");
ReadLine();
}
Expression Bodied Members
Lambda Expressions are very useful when you are working with
LINQ query. But in C# 6.0 you can use lambda
expressions with properties
and functions to
increase your productivity and write clean code.
Using lambda expressions, you can define the method in one
line, it means use only for simple and short logical methods or properties. I believe when you
are working with large application and you need to get single value based on their condition
then there we can use the expression bodied members.
We
can directly create
a function and
also get the
output based on
their parameters values.
Before C# 6.0
Earlier we generally use to create a separate method to
complete any simple task; it might be one liner or more than one line. But it gets quite complex
and takes time. See the following example where the two methods GetFullName and AddTwoNumber
are doing simple task like concatenating two strings and add two numbers. But to
complete this task, we had written two separate methods.
public class Program
{
public static
string GetFullName(string firstName, string lastName)
{
return
string.Format("{0} {1}", firstName, lastName);
}
public static
int AddTwoNumber(int firstNumber, int secondNumber)
{
return
firstNumber + secondNumber;
}
static void
Main(string[] args)
{
string firstName =
"Mukesh";
string
lastName = "Kumar";
int
firstNumber = 10;
int
secondNumber = 20;
Console.WriteLine("Full Name is "+GetFullName(firstName,
lastName));
Console.WriteLine("Sum of Two Number is
"+AddTwoNumber(firstNumber,
secondNumber));
Console.ReadLine();
}
}
In C# 6.0
C# 6.0 does not required to create separate methods for only
single task. It can be defined and completed at that time when it is defining. Using the lambda
expression, we can simply write linear method.
using static System.Console;
namespace CSharp6FeaturesDemo
{
public class
Program
{
public static
string GetFullName(string firstName, string lastName) =>
firstName + " " + lastName;
public static
int AddTwoNumber(int firstNumber, int secondNumber) =>
firstNumber + secondNumber;
static void
Main(string[] args)
{
string
firstName = "Mukesh";
string
lastName = "Kumar";
int
firstNumber = 10;
int
secondNumber = 20;
WriteLine("Full
Name is "+GetFullName(firstName, lastName));
WriteLine("Sum of two number is "+AddTwoNumber(firstNumber, secondNumber));
ReadLine();
}
}
Getter Only Auto Properties
When you are working with properties, Before C# 6.0 we need
to define the getter and setter both; but in C# 6.0 we can define only the getter for
properties and make it read only. Before C# 6.0 you need to
define the both
when going to
create properties.
Sometimes,
it is not required to create the setter but we need to define it. But
there is not any restriction to make such type of coding with C# 6.0.
You can only define the
getter for the properties and make it read-only.
See the following example where FirstName and LastName have
their getter with their values.
In C# 6.0
public class Program
{
string
FirstName { get; } = "Mukesh";
string
LastName { get; } = "Kumar";
public string
FullName = string.Empty;
public
Program()
{
FullName =
FirstName + " " + LastName;
}
static void
Main(string[] args)
{
Program
prog = new Program();
Console.WriteLine("The Full Name is " + prog.FullName);
Console.ReadLine();
}
}
Exception Filters
It is available with VB but when new compiler
"Roslyn" is introduced. This feature added with it.
Exception Filter is used to specify the catch block on the
basis of some conditional argument.
Generally we define
only one catch
block and inside
that we make
different conditions for throwing the different types of exceptions.
But in C#
6.0 you can check the
message and show
the exception message
as per your conditions.
Before C# 6.0
static void Main(string[] args)
{
int
errorCode = 404;
try
{
throw
new Exception(errorCode.ToString());
}
catch
(Exception ex)
{
if
(ex.Message.Equals("404"))
Console.WriteLine("This is Http
Error");
else
if (ex.Message.Equals("401"))
Console.WriteLine("This is Unathorized Error");
else
Console.WriteLine("This is some different exception");
Console.ReadLine();
}
}
In C# 6.0
With C# 6.0, we can check the exception message and ,on the
basis of which, exception can be defined in the catch block.
It can be used with multiple catch
blocks and every catch block will be checked
with its own conditional message.
using static System.Console;
namespace CSharp6FeaturesDemo
{
public class
Program
{
static void
Main(string[] args)
{
int
errorCode = 404;
try
{
throw
new Exception(errorCode.ToString());
}
catch
(Exception ex) when (ex.Message.Equals("404"))
{
WriteLine("This is Http Error");
}
catch
(Exception ex) when (ex.Message.Equals("401"))
{
WriteLine("This is Unathorized Error");
}
catch
(Exception ex) when (ex.Message.Equals("403"))
{
WriteLine("Forbidden");
}
ReadLine();
}
Null Conditional Operators
The
null-conditional operator translates
to checking whether
the operand is
null prior to invoking the method
or property. We
check the object
is null or
not so that NullReferenceException could not occurs or handled properly.
But to implement this we need to write some extra code which sometimes makes the code
lengthy.
But with C#
6.0, you don't
need to write
some extra code,
you can use
null conditional operator, which is nothing but only a question mark [?]
sign.
Before C# 6.0
public class Program
{
static void
Main(string[] args)
{
List<Employee> employees = new List<Employee>();
Program
prog = new Program();
if
(employees.FirstOrDefault() != null)
{
//This
code will not hit because of employees is null;
Console.WriteLine(employees.First().Name);
}
else
{
Employee emp = new Employee();
emp.EmployeeId = 10;
emp.Name = "Mukesh Kumar";
emp.Address = "New Delhi";
employees.Add(emp);
Console.WriteLine(employees.First().Name);
}
Console.ReadLine();
}
}
public class
Employee
{
public int
EmployeeId { get; set; }
public string
Name { get; set; }
public string
Address { get; set; }
}
}
In C# 6.0
using static System.Console;
public class Program
{
static void
Main(string[] args)
{
List<Employee> employees = new List<Employee>();
Program
prog = new Program();
//No need
to check null in if condition
//null
operator ? will check and return null if value is not there
WriteLine(employees.FirstOrDefault()?.Name);
//set the
default value if value is null
WriteLine(employees.FirstOrDefault()?.Name
?? "My Value");
ReadLine();
}
}
public class
Employee
{
public int
EmployeeId { get; set; }
public string
Name { get; set; }
public string
Address { get; set; }
}
See, First value is not going to print anything and also not
throwing any error.
It is because the? Sign is included
with the statement
which handles the
null exception.
And
for the second statement the default value "My Value" will be
going to print because of the value is null.
Chaining using Null Conditional Operator
What makes the null-conditional operator more useful is that
it can be chained. If, for example, you invoke
string[] names = person?.Name?.Split(' '),
Split will only be invoked if both person and person.Name are not null.
When chained, if the
first operand is null, the expression evaluation is short-circuited, and
no further invocation
within the expression
call chain will
occur.
nameOf Expression
nameOf
expression feature for
C# 6.0 has
introduced with CTP3
update. Sometime there
is requirement to pass the parameter name as it is as string in
our code. It is called Magic strings.
It is normal string which is mapped to code.
In big application
where thousands of
line written, if
we pass the
string value inside
the “” [double quotes] and we need to change the parameter name as
well as magic string name then it is very hard to find out each and replace to everyone.
But using nameOf expression, we don’t need to care
about magic string
inside the code.
Just change the
parameter name at
every place.
Await in Catch/Finally Block
0 comments:
Post a Comment