Direct Casting, IS and AS Operator in C#

Hello friends,

Below are the available ways in C# when you cast one data type to another.

Direct casting

Direct cast is most common way of casting one type to another, however it yields exception if casting can’t be done.

Below is the example to demonstrate the same.

object length = 3.2;

int test = (int)length; //Fails in runtime

Console.WriteLine(test);

is operator

is operator checks whether an object is compatible with a given type (on the right side) and the result of the evaluation is either true (if casting can be done) or false (if casting can’t be done) and since the result is always a Boolean value so there is no chance of runtime exception.

Below is the example to demonstrate the same.

object length = 3.2;

if (length is int) //Check if length can be cast to int

{

Console.WriteLine(length);

}

as operator

The as operator is like a casting except that it yields null on conversion failure instead of raising an exception. So runtime exception can be avoided using null check.

Below is the example to demonstrate the same.
class MyClass //Sample class to test the scenario

{

int a;

string b;

}

static void CastMe()

{

name = new MyClass();

string test = name as string;

if (test != null) //Check if test is not null means i.e. casting can be done

{

Console.WriteLine(name);

}

}

Hope you liked the post. Please share your comments.

Working With Async Main In C# 7.1

Hello folks!

I am here to present the series related to C# 7.1’s new features. In the first part, we will be going through one of the important features called async main.

async main

Starting with C# 7.1, the main function that is the entry point of the application can have async. Before C# 7.1, the main function could have a return type as either void or int; however now, it also supports Task and Task<int>.

Main overrides (Before C# 7.1) Main overrides (In C# 7.1)
  • static void Main();
  • static int Main();
  • static void Main(string[] args);
  • static int Main(string[] args);
  • static void Main();
  • static int Main();
  • static void Main(string[] args);
  • static int Main(string[] args);
  • static Task Main();
  • static Task < int > Main();
  • static Task Main(string[] args);
  • static Task < int > Main(string[] args);

Let’s take a few examples to understand more.

Before C# 7.1, when you wanted to call async method from Main, you needed to add some boilerplate code but now, C# compiler does it for you and, in turn, enforces crisp coding by adding the required code automatically.

Let’s try to understand this by a simple example as following.

Before C# 7.1

  • using System.Threading.Tasks;
  • using static System.Console;
  • namespace CSharp7PlusDemo
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {
  •             Title = “C# 7.1 demo”;
  •             WriteLine($“Hello Prakash!!, I am from < C# 7.1 at {System.DateTime.Now}”);
  •             Task.Delay(2000).GetAwaiter().GetResult();
  •             WriteLine($“Hello Prakash!!, I am from < C# 7.1 at {System.DateTime.Now}”);
  •         }
  •     }
  • }

Output

Output

In C# 7.1

  • using System.Threading.Tasks;
  • using static System.Console;
  • namespace CSharp7PlusDemo
  • {
  •     class Program
  •     {
  •         static async Task Main(string[] args)
  •         {
  •            WriteLine($“Hello Prakash!!, I am from C# 7.1 at {System.DateTime.Now}”);
  •            await Task.Delay(2000);
  •            WriteLine($“Hello Prakash!!, I am from C# 7.1 at {System.DateTime.Now}”);
  •         }
  •     }
  • }

Output

Output

As you can see that Task.Delay is adding 2 seconds. Now, C# 7.1 syntax is crispier and easy to use.

So we just looked at how we could use the Task with Main. Now, let’s take another example where we will demonstrate the use of Task<int>.

Here, we will call another async method (FactorialAsync) from Main.

  • using System.Threading.Tasks;
  • using static System.Console;
  • namespace CSharp7PlusDemo
  • {
  •     class Program
  •     {
  •         static async Task<int> Main(string[] args)
  •         {
  •             Title = “C# 7.1 demo”;
  •             var number = 5;
  •             WriteLine($“Factorial of {number}: {await FactorialAsync(number)}”);
  •             return 0;
  •         }
  •         private static Task<int> FactorialAsync(int n)
  •         {
  •             return Task.Run(() => Cal(n));
  •             int Cal(int i)  //Local function
  •             {
  •                 if (i == 1)
  •                 {
  •                     return 1;
  •                 }
  •                 else
  •                 {
  •                     return i * Cal(i – 1);
  •                 }
  •             }
  •          }
  •      }
  • }

Output

Output

You can also see that in the above example, we have used a Local function that is the feature of C# 7.0. Moreover, we can also use expression-bodied method (introduced as part of C# 6.0) to call the async method directly from Main, as following.

static async Task Main(string[] args) => WriteLine($“Factorial: {await FactorialAsync(5)}”);

Output

Output

Conclusion

In this article, we have looked at one of the quite useful features “async main”, introduced as part of C# 7.1. We have seen how to use Task and Task<int> with Main. On the sideline, we have also seen the use of Local function and expression bodied method.

Hope you liked the article. I look forward to your comments/suggestions.

References

  • https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1
  • https://blogs.msdn.microsoft.com/dotnet/2017/10/31/welcome-to-c-7-1/