New Feature in C# 7.1 – Inferred tuple element names

From past few years I have been keeping a close watch on ECMA scripts and seems C# is running neck to neck in importing features of ES-6

I have explained about Tuples in older Blog article here

C# 7.1 introduces a small feature enhancement to Tuple de-structuring.

To run below sample you need to install System.ValueTuple Nuget package


style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">


Continue reading

New Feature in C# 7.1 – default Literal expressions

default value expression provides a default value for a type and are very handy in generator functions and generic classes/methods.

This is how we can use default keyword till C# 7.0 i.e. as default(T) where T can be value type or reference type

private void btnDefaultExpressions_Click(object sender, EventArgs e)

{

string str = default(string); //Old way of defining default strings

 

var intValue = default(int);

 

string stringValue = default(string);

 

var nullableIntValue = default(int?);

}

Continue reading

New Feature in C# 7.1 – Async Main

“Main” is a special method while defining assemblies. It’s an entry point of an executable application. Main runs in static context by is called by operating system to load the program into memory. Main does so by defining a startup object or logic.

static class Program

{

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        static void Main(string[] args)

{

}

}

Continue reading

C# 7.1 New Features – Set up Visual Studio

In my past blog series, I have tried to explain all new features that shipped with C# 7.0. You can read about that here.

With Visual Studio Update 3 and version 15.3, C# 7.1 has been made available as well. This feature is not available by default and there are many ways you can turn this feature on. I will be writing a blog series on new features of C# 7.1 but before that lets understand how to set up support for 7.1 in visual studio.

There are 3 ways this feature can be enabled:

Way 1 – Changing Project Setting to target latest C# language

Continue reading

C# 7.0 New Features – Throw expressions

C# developers have always used throw statement to throw unhandled exceptions to caller. A reactive programming approach involved validating the variable values and if it doesn’t fall within a valid range or is null throw exception as demonstrated in below example

//Method that fetches data from server 
object Getdata()
        {
            //Fetch data from server or database and if data is null return null
            return null;//
        }

        private void btnThrowExpressionAlternateC6_Click(object sender, EventArgs e)
        {
            var data = Getdata();
            if (data == null)
                throw new Exception("No Data found");

        }

Continue reading

C# 7.0 New Features – Pattern Matching

Pattern matching is a feature that allows you to implement method dispatch on properties other than the type of an object. Pattern matching is very useful when we want to create branching logic based on arbitrary types and values of the members of those types.

Object dispatch is a very common feature of object oriented programming wherein we identify objects based on their type and call appropriate method. Based on resolved type the method gets dispatched on appropriate type i.e. child or base. This feature is automatically implemented if we use concept of object oriented programming like Hiding and Overriding.

Problem occurs when there are multiple classes that our code uses and the classes are not related to each other. In that case the branching logic requires below steps to correctly dispatch method call to object:

  • Identify type of object using various branching logic
  • Cast to appropriate type if needed
  • Call method on object

Example in C# 6.0:

Continue reading

C# 7.0 New Features – Tuples Enhancements

Many a times we would like to return more than one values from a method call. C# provided lot of features to support this functionality. Some of them are:

  • Out Parameter
  • Ref Parameter
  • Anonymous types can be returned via dynamic keywords
  • Tuples

C# 4.0 introduced a type Tuple<…> using which you can return more than one value from a function without creating a new type. Tuple behaves like a dictionary with each returned item accessible as Item1, Item2 and so on. This is very verbose and require a Tuple object to be created.

Example using C# 4.0

  Tuple<int, int> ReturnRuntimeTimeEncapsulatingTwoValues()
  {
      return new Tuple<int, int>(1, 2);
  }

  private void btnTuple6_Click(object sender, EventArgs e)
  {
     Tuple<int, int> tuple = ReturnRuntimeTimeEncapsulatingTwoValues();
     //Usage in c# 6
     int value1 = tuple.Item1; //No control over member name and its too unintuitive
     int value2 = tuple.Item2;
  }

Continue reading

C# 7.0 New Features – Local functions

Local functions are another very handy feature to be introduced into language if you are into code refactoring. Many a times developers create a very large method and while code review we see lot of places same logic has been repeated and thus think about refactoring it. Problem is that if the logic is required only at multiple places within same method than it’s not a good idea to make it into a separate named method.

Let’s take an example in C# 6 and then we will try to refactor that using various ways and finally with local functions feature in C# 7.0

Here is a simple code that works on array of numbers and calculates sum and subtraction of each number in array

style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">



Continue reading

C# 7.0 New Features –More Expression Bodied Members

Expression bodied members were introduced in C# 6.0. You can read more about those here

C# 7.0 introduced more stuff like accessors, finalizer’s and constructors as expression bodied members

Expression Bodied Syntax for constructors

public CSharp7Features(string someData) => Console.WriteLine("Constructor called with {0} in c# 7 feature", someData);

Expression Bodied Syntax for Finalizers


Continue reading

C# 7.0 New Features –Return Locals as Refs

Important points regarding ref in C#

  • ref keyword is used to return more than one values from a function.
  • ref keywords need to be defined before you can pass them as a parameter to function
  • Called method is not bound to assign any value to the ref parameter since it has already been initialized by calling method

Case Study

We need to find if a number i.e. 4 exist in an array and if exist we would like to change its value to 111

Example using C# 6.0

Consider below extension method which returns index of a number if it’s found in array

Continue reading

C# 7.0 New Features – Literal Improvements

C# 7.0 introduces Number literals as well as Binary Literals

These are completely new features that adds syntactic sugar to C# while dealing with number and binary data.

You can now declare numeric variables as below while adding (Underscore) _ as a separator for readability. This is handy while dealing with large numbers

One important thing to understand about these separator literals is that these are ignored by compiler while evaluating the value and are just meant to provide readability.

Continue reading

C# 7.0 New Features – Out Parameter Enhancements

out/ref keyword has been used to return more than one values from a function.
ref keywords need to be defined before you can pass them as a parameter to function but on the other hand out variables need not be initialized before they can be passed as a parameter to a function.
In case of ref, the called method is not bound to assign any value to the ref parameter since it has already been initialized by calling method but in case of out, the called method has the responsibility of assigning value of out parameter failing which results in a compile time error.
Problem with the out keyword in past was that we need to declare out Parameter before it can be passed as argument
Before C# 7.0
Usage of out parameter

Continue reading