Using Static Statement
We all know that you can import a
namespace with using. This gives us the ability to use a type with
just the type’s name in our code.
using System;
public class Driver
{
public static void Main()
{
// without importing a namespace, we'd have to fully qualify the type
// Console as System.Console
//System.Console.WriteLine("Hello, World!");
Console.WriteLine("Hello, World!");
}
}
In C#6.0, import the static members
of a class into our namespace , making them available without qualification in
subsequent code:
using static System.Console;
public class Driver
{
public static void Main()
{
// Now, the System.Console static class is imported, so we
// can use WriteLine directly
WriteLine("Hello, World!");
}
}
void Main()
{
MyStaticClass.Print("this
string"); //Print is a static
member in MyStaticClass
//
or...
Print("this
string");
}
Importing static types and accessing extension methods of them like the code above will give you an
error. The following code will generate the "The name 'IsPolygon' does not
exist in the current context".
Non-extension static methods are
invoked as though they are methods on the current type, whereas extension
methods are invoked only as though they are methods on a variable.
Read only Property
and initialization
Public string
Name {get;} = “XXXXX”; or public string Name => “XXXX”;
Expression-Bodied Get-Only Properties
Expression-Bodied Get-Only Properties
Now, if you have a property that is
get-only, you can write the body of the property using the expression syntax.
That is, you can use the lambda-expression syntax to write the body of the
property.
That is, instead of writing
the { get { return your expression; } } syntax,
we can simply write => your expression;
For example, if we convert our
get-only properties above, we can get:
1: public class Rectangle
2: {
3: public int Length { get; set; }
4: public int Width { get; set; }
5:
6: // much more concise! Read Only properties
7: public int Area => Length * Width;
8: public int Perimeter => 2 * (Length + Width);
9:
10: public override string ToString()
11: {
12: return $"Rectange: Length={Length}, Width={Width}";
13: }
14: }
It does not create a delegate, it
is simply borrowing the lambda expression syntax to simplify writing simple
bodies that result in an expression.
After lambda express we always have single statement.
Expression-bodied
function members can work for both
methods and properties. If you have
a method with one statement, and that statement can be represented as an
expression:
public string GetFullName() {
return FirstName +
" " + LastName;
}
Or a getter-only properties/indexers with a body that can be
represented as an expression:
public string FormalName {
get { return
FirstName[0] + ". " + LastName; }
}
Public object TestObj {get {return obj;}} //Read only property
You can collapse those down into something that looks like a
cross between a member declaration and a lambda expression:
public
string GetFullName() => FirstName + " " + LastName;
public
string FormalName => FirstName[0] + ". " + LastName;
public
object TestObj => obj; //Read only
property in C#6.0
Null Propagation Operator
In earlier
versions of the C# language, we always had to write an if condition for a null check before using an object or
its property. Now C# 6.0 has introduced the Null-Propagation Operator (?.) that
enables developers to check for the null value within an object reference
chain. The null-propagation operator (?.) will return null if anything in the object reference chain is null.
Example 1
In
earlier versions of the C# language, you always had to check for nulls explicitly before
using an object or its property, as shown below:
Hide Copy Code
if (Employee.Name == null)
{
Console.WriteLine("No Employee name provided");
}
The
same can be converted into a one-liner using the Conditional Access Operator in
C# 6.
Hide Copy Code
Console.WriteLine(Employee?.Name
?? "No Employee name provided");
Example 2
Suppose
we have a class called Student that has another property studentdetails of
type Details class. Now we can have the following code snippet to print
theAddress .
Hide Copy Code
if (student != null &&
student.studentdetails != null)
{
Console.WriteLine(student.studentdetails.Address);
}
else
{
Console.WriteLine("No Address");
}
As
we can see, to avoid the null-reference exception, we have checked
the null for student andstudent.studentdetails since they can have a null reference as object. So, the preceding
code snippet can be re-written using the null propagation operator (?.) as follows:
Hide Copy Code
Console.WriteLine(student?.studentdetails?.Address ?? "No Address");
Both
code snippets will provide us the address of the student.
What
I think is, it's a really nice feature because instead of checking each and
individual objects, using the nullpropagation operator (?.) we can check the
entire chain of references together and whenever there is a nullvalue in the entire
chain of reference, it will return null.
nameof Operator
nameof operator allows you to
retrieve the name of a variable, type or member.
Use the
nameof
operator to avoid the use of hard-coded string
s in our
code.
This operator will help us get rid of “magic strings” in our
code. We all know following use case:
public void Method(int arg)
{
if (arg < 0)
{
throw new ArgumentOutOfRangeException("arg");
}
}
With nameof
operator we can rewrite code in a nicer way:
public void Method(int arg)
{
if
(arg < 0)
{
throw new ArgumentOutOfRangeException(nameof(arg));
}
}
That is! nameof
just returns a string representation of variable\method\type\propery\field.
String Interpolation
This feature inserts values into a string with simple
syntax. It is similar to string.Format, but variables may be accessed directly
string name =
"Valentino";
int age = 7;
var data1 =
string.Format("name:{0}, age:{1}", name, age);
Console.WriteLine("classic
string format - {0}", data1);
var data2 = $"name:{name},
age:{age}";
Console.WriteLine("string
interpolation - {0}", data2);
Console.ReadLine();
Exception Filters
It allows us to specify conditions along with a catch block. The catch
block is only executed if the condition satisfies.
public void Main()
{
try
{
throw new Exception("E2");
}
catch(Exception ex) when(ex.Message == "E1")
{
Console.WriteLine("caught E1");
}
catch(Exception ex) when(ex.Message == "E2")
{
Console.WriteLine("caught E2");
}
}
Setting
default values to Auto Properties
Now we can assign default
value to the properties without writing a second line. Just place an “=”
equal sign at the end and write the default value to it.
Earlier we used to have to
do this by setting the default value in the constructor
public string FirstName { get; set; } = "Default Value";
No comments:
Post a Comment