Features of C# 7.0

cover

 

 

 

 

C# 7.0 Features

Last article we have looked the features of C# 6.0, so in this article we will see the features of C# 7.0

C# 7.0 March 2017 .NET Framework 4.6.2 Visual Studio 2017

out Keyword

The out parameter can be used to return the value in the same variable and as a parameter of the method, if any changes made to that parameter it will reflect the changes to that out variable.

In earlier version

old_Out

In C# 7.0

Here no need to declare it separately, specify directly in the argument itself.

New_Out1

Tuples

C# tuples as richer anonymous types, it’s a set of elements.

Old-Tuple

You can access name and age by referencing Item1 and Item2.

In C# 7.0

Here we can directly get the name and age instead of Item1 and Item2

New_Tuple

Discards

Discards are equivalent to unassigned variables, that variable may not even be allocated storage

They don’t have names, instead, they are represented as a _ (underscore.)

Discards

 

 

 

 

 

Pattern Matching

It’s not new to C#, in the earlier version itself introduced but in the coming version its added some more features in the implementation.

  • Pattern matching has the ability to extract the data from the expression.
  • Pattern matching can be used with any data type including custom whereas if/else can only be used with primitive types.

In C# 7.0, introduced 2 more features like “Is expression” and “Switch case statement”

With “Is” pattern

Is_Pattern

Pattern with Switch…case statement

Now Switch…case statement also works with expression as well.

Switch_Pattern

Ref local and returns

Ref Locals

Before C# 7.0 it was not possible to declare the return type with the ref modifier. While this feature was available using IL code, the feature was not reflected with C#. This changes with C# 7.0. However, before looking into this, let’s get into another new C# 7.0 feature: ref locals. Local variables can be declared with the ref modifier. Here, the variable x1 references variable x, and thus changing x1 changes x as well

Ref_Locals1

 

 

 

output: local variable x after the change: 2

Ref Returns

The ref keyword can also be used with the return type. This allows code as shown in the following code snippet. Here, an array of type int is declared and initialized. In the next line, a local ref variable is declared that references the first element of the array. This variable is then returned in the last statement of the method

Ref-Returns

 

 

 

 

Local Functions

Local functions enable you to define a function within the scope of another method to help in promoting encapsulation and bring local variables into scope.

LocalFunction

 

 

 

 

 

 

 

 

 

More expression-bodied members

Expression-bodied methods was introduced with C# 6.0, that simplify the syntactic expression for methods in C#. We have seen this for Methods and Properties in the previous version of C#. C# 7.0 extend this features for several new members including constructor, destructor, property assessors etc.

In earlier version

MoreExpressionBodies1

 

 

 

 

 

In C# 7.0

NewExpressionBodyFunctionMember1

 

 

 

 

 

Throw expression

C# 7.0 introduces throw expressions. We can add exception throwing to expression-bodied members, null-coalescing expressions and conditional expressions. This blog post introduces throw expressions, demonstrates how to use them and also provides a peek behind a compiled throw expression.

Throw expression

Generalized async return type

Running a Task from async methods can introduce performance bottlenecks in certain paths.

Ever since C# 5.0 when the async/await pattern was introduced, the only supported return types were Task<TResult>, Task, and void

Generalized asyn return

If the directory is empty, the known space is 0 and there is no need for an asynchronous thread to calculate the size.  However, since Task<long> is the return, it still needs to be instantiated.

By using ValueTask<….> we don’t want to instantiate the Task<long>, it can return Task or Task<long> and so on.

New_Generalized asyn return

Numeric literal syntax improvements

The digit separator “_” can be used inside number literals now. The purpose of a digit separator is to improve readability, nothing more

public const int One = 0b0001;

public const int Two = 0b0010;

public const int Four = 0b0100;

public const int Eight = 0b1000;

public const int Sixteen = 0b0001_0000;

Note: 0b -> indicates as binary

 

Conclusion

I hope this article will help much to understand the features of C# 7.0, in the next article we will see the features of C# 7.1 and 7.2

Features of C# 7.1 and 7.2

Cover

C# 7.1 Features

In the previous article we have looked in to the features of C# 7.0,  in this article we will see the some of the features  introduced in C# 7.1 and 7.2

C# 7.1 August 2017 .NET Framework 4.6.2 Visual Studio 2017 version 15.3

Default literal expressions

When we declare the local function or variable or methods until C#7.0 we need to instantiate that in the code, but the newer version of C# not necessary to create a default type of that value.

In C# 7.0

Old_Default literals

In C# 7.1

Here we don’t want to specify the type of the function or variable, by default its taking.

New_DefaultLiterals

 

 

 

Tuple Name inferred

The names of tuple elements can be inferred from tuple initialization in many cases.

In C# 7.0

TupleNameInferred_Old

 

 

 

 

 

In C# 7.1

Here we don’t want to give the name, its taking from the variable name itself.

TupleNameInferred_New

Async and Await in Main method

The purpose of it is for situations where your main method calls one or more async methods directly. Prior to C# 7.1, you had to introduce a degree of ceremony to that main method.

AsyncMain

 

 

 

 

 

 

In C# 7.1

New_Asyncawait

 

 

 

 

 

 

 

Pattern Matching with Generics

We have already got enough information about Pattern matching in C# 6.0 itself, now in C# 7.0 added some additional feature like “Pattern Matching with Generics”, in the previous version there is a design flow in the pattern matching with switch case statement.

Old-GenericPattern

Here the compiler indicates an error, because we cannot match the pattern with generics, so in order to avoid the problem in the next version introduced the feature.

New-patternMatching

 

 

 

 

 

 

 

 

 

 

C# 7.2 Features

Private Protected

This is the new access modifier in C#, previously we had private, public, protected and so on, this feature is enable the possibility to access the private member from the parent class and that too within the same assembly.

PrivateProtected

Non-trailing named arguments

In C# 4.0 a new type of argument is introduced known as a named parameter. Using this feature, we can specify the value of a parameter by parameter name regardless of its ordering in the method.

Non-trailing named arguments

 

 

 

 

 

 

 

Here we can give the parameter in any order with the specified named parameter.

Leading underscores in numeric literals

The implementation of support for digit separators in C# 7.0 didn’t allow them _ to be the first character of the literal value. Hex and binary numeric literals may now begin with an _.

Reference semantics with value type

out: option to set the value

ref: Should set the value before passing it.

in: This method does not modify the value of the argument used as this parameter.

The “in” keyword specifies that you are passing the parameter by reference and the called method does not modify the value passed to it.

 

Conclusion

I hope this article will help much to understand the features of C# 7.1 and 7.2.

 

C# 6.0 Features Overview

C# 6.0 Features.

C# is a general-purpose programming language, it’s an elegant and type-safe object-oriented language that enables developers to build a variety of robust, secure applications in .NET framework.

C# 6.0 July 2015 .NET Framework 4.6 Visual Studio 2015

Read-Only Properties

Properties are an extension of data field in C#, data fields are not directly accessible from outside class, we must use the GET, SET methods to access it.

Properties

 

 

 

 

In general, read only properties allows the properties to set only inside the scope, outside classes can only read.

Properties_PrivateSet

 

 

 

 

In C# 6.0, it is not necessary to specify the private set, by default it’s a read-only property when we don’t have a SETTER

Properties_Get

 

 

 

Auto-Property Initializer

An auto-property initializer allows you to set the value of the property at the same time you declare it in a class, in the earlier version we need to set the property value in the constructor.

In earlier version of C#

PropertySetInConstructor

 

 

 

 

 

 

In C# 6.0

Auto-Property Initializers

 

 

Expression bodied function member

Expression-bodied function members allow properties, methods, operators and other function members to have bodies as lambda like expressions instead of statement blocks. Thus, reducing lines of codes and clear view of the expressions.

In earlier version of C#, the function will be like.

Old-MethodNotanExpression

 

 

 

In C# 6.0

NewExpressionBodyFunctionMember

So, we can directly write the body as an expression here.

Using static

The using static enhancement; enables you to import the static methods of single class. Previously, the using statement imported all types in a namespace.

In earlier version

Using_Static_Old

 

 

 

C# 6.0

Using_Static_Old

 

 

 

Null-conditional operators

It’s a new feature in C# 6.0 which will bring more productivity for the developers by reducing the number of lines.

In earlier version

NullCondition_Old

 

 

In C# 6.0

NullCondition_New

 

 

String interpolation

This feature inserts values into a string with simple syntax. It is similar to string.Format, but variables may be accessed directly (not through index arguments).

In earlier version

StringInterpolation_Old

 

 

 

In C# 6.0

StringInterpolation_New

 

 

 

 

Exception filters

If you want to use Exception Filter, you have to declare it in the same line where you declared the catch block, just like this: catch (Exception ex) if (FilterIsTrue). Here, if the parenthesized expression after the “if” returns true, the associated catch block will execute. Otherwise, it will move forward.

ExceptionFilters

 

 

 

 

 

 

 

nameof Expressions

Evaluates to the name of a symbol

In earlier version

nameOf_Old

 

 

 

 

In C# 6.0

nameOf_New

 

 

 

 

Await in catch and finally blocks

In earlier version of C# itself we can use try, catch and finally blocks together but was not able to use the Async and await in catch and finally blocks, so the next version of C# 6.0 introduces the features to use the await in catch {} and finally {} blocks without any complicated structure.

The await operator is applied to a task in an asynchronous method suspend the execution of the method until awaited task completes, the asynchronous method in which await is used much be modified by the Async keyword.

AwaitInCatchAndFinally

 

 

 

 

 

 

Index initializers

Initializing dictionaries and other objects with indexers is less elegant. We are adding a new syntax to object initializers allowing you to set values to keys through any indexer that the new object has

In earlier version

IndexInitializer_Old

 

 

 

 

 

In C# 6.0

IndexInitializer_New

 

 

 

 

 

 

Conclusion

I hope this article would help to understand the features of C# 6.0, in the next article we will see the features of C# 7.0