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

Asp.Net Core 2 – Runtime Store

Welcome to the series of asp.net core tutorials, in this part we will discuss another new feature that has shipped with asp.net core 2.0

Let’s first discuss 2 problems faced by monolithic applications:

  • All packages need to be deployed for application to run correctly and for different target environments there were challenges in picking the right version of package.
  • Since packages are not precompiled the application load time becomes slow

To overcome these issues Asp.net core 2.0 has introduced the concept of runtime store using which you can package and deploy applications against a known set of packages that already exist in target environments.

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

Install and running .Net core

Step 1:

Download and install .net core sdk from

https://www.microsoft.com/net/download/core

if you already have Visual studio installed you can install “Visual Studio 2017 Tools” else install “Windows (x64) Installer” if you want to work from command line only

Core1

Step 2:

When setup finishes it will install all required tools and also setup the path variable so that all CLI tools are available via command line

Continue reading

Creating first application using Bot Framework

In this article series, we will create and run our first application using Bot framework template installed in previous article.

Start Visual Studio, go to File -> New Project and select Bot Application template under Visual C#. Name the project say HelloBots and click OK button.

First1

Here is how the created project looks like

Continue reading

Setting up Visual Studio to use Bot Framework

Please refer to article 1 in series of instruction to bot framework to know more about Bot framework here

Bot builder SDK is available as a Nuget package names “Microsoft.Bot.Builder” and required .Net Framework 4.6 or above versions. You can also download the source code for Bot framework here

To setup visual studio for Bot Application development. follow below steps:

  • Download Visual studio 2015/2017 from http://www.visualstudio.com
  • Update all Visual Studio Extensions from (Tools -> Extension and Updates -> Updates)
  • Download Bot Application templates from here
  • Navigate to %UserProfile%\Documents\Visual Studio 2017\Templates\ProjectTemplates\Visual C#\

SetupVs1

Continue reading

Introduction to Microsoft BOTS Framework

Bots are an integral part of user’s experience in today’s digital world. Bots can be thought of as applications that performs automated tasks e.g. interact with user and thus eliminating the need for manual support. Some examples of bots from daily life are Cortana And Siri. You can interact with them using text or speech, does some background processing and generate response for you. There are many ways a bot can interact with a user:

  • Text
  • Cards
  • Speech

Typically, while interacting with users, bots use pattern matching algorithms to generate responses from stored set of responses. Creating something like this from scratch can be a real pain but with the improvements in Artificial intelligence techniques and more so with Microsoft’s Cognitive services which provides support for natural language processing, speech and image recognition, lot of things are now available out of the box.

Continue reading

Asp.Net Core 2 – ASP.NET Core metapackage

As you might already be aware Asp.net core is a platform made of nuget packages. There are different packages targeting different version of frameworks available say .net 4.6, Asp.net core 1.0,1.1 and 2.0. We generally classify frameworks into 2 categories:

  • Traditional framework e.g. .net 4.6 which includes .Net framework where most of things are predefined and need not be configured
  • Package-based frameworks which are created entirely from scratch by choosing packages as and when required

Package based frameworks are not easy to use and required a different/higher level of understanding of all required packages and most of the .net developers are used to work with predefined templates provided by visual studio.

This problem has been work around by introducing the concept of metapackages which are a collection of commonly used packages required by apps.

In older versions of .net core tools (both project.json and csproj-based tools) by default specified both a framework and a metapackage but in later versions metapackages were tied to specific frameworks . Depending on targeted framework appropriate metapackage is already added to project. This feature is also called as implicit referencing of metapackages. For example

Continue reading

Asp.Net Core 2 – Razor Pages Support

Razor pages support has been added to asp.net core MVC which makes coding page-focused scenarios easier and more productive. Razor page support is enabled in Startup.cs file as

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Includes this line to support for Razor Pages and controllers.
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }
}

Continue reading

Asp.net core 2.0 New Features

Microsoft recently announced Asp.net version 2.0 with lot of new and exciting features and enhancement. This update comes on top of the first version i.e. Asp.net Core 1.0 also known as Asp.net 5.0.  To install Asp.net core 2.0 update:

Install Visual Studio 15.3 or later with the following workloads:

  • ASP.NET and web development
  • .NET Core cross-platform development

Various new features that have been shipped with asp.net core 2.0

  • Razor Pages Support
  • NET Core metapackage
  • .NET Standard 2.0
  • Runtime Store
  • Configuration update
  • Logging Update
  • Authentication update
  • Identity Update
  • Kestrel improvements
  • WebListener renamed to HttpSys
  • Hosting startup and Application Insights
  • Automatic use of anti-forgery tokens
  • Automatic precompilation
  • Razor support for C# 7.1

Continue reading