Friday, December 28, 2018

Visual C# Technical Guru - November 2018

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - November 2018
Happy Coding.

Regards,
Jaliya

Thursday, December 20, 2018

Visual Studio 2019: Start Window

I am sure most of you are already experiencing the new Visual Studio 2019, and you definitely must have seen the new Start window.
image
Visual Studio 2019: Start Window
Personally, I like the previous Start Page, and if you feel like you are missing it in Visual Studio 2019, you are not. Go to Tools –> Options –> Environment –> Startup and change On startup, open to Start Page.
image
Startup Options
Now restart Visual Studio, and when starting up, you will see that Visual Studio will open the Start Page and not the Start window.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, December 13, 2018

.NET Core 2.2: Executing Code Prior to Main Method

Last week .NET Core 2.2 was released with some nice features and in this post, let’s see one of them which is executing code before the Main method.

As we all know the Main method is the entry point of a program. But .NET Core 2.2 is introducing this feature called Host startup hook and it provides a mechanism to execute code before executing the Main method.

I have created two class library projects named StartupHook1 and StartupHook2 and both of them are targeting .NET Core 2.2. Inside both of the projects, I am adding a class named StartupHook.
using System.Diagnostics;
using System.Reflection;
 
internal class StartupHook
{
    public static void Initialize()
    {
        Debug.WriteLine($"{Assembly.GetExecutingAssembly().GetName().Name} is called.");
    }
}

Note: The type must be named StartupHook without any namespace and it should be internal. And inside the class, we should have a static method named Initialize. For the sake of the post, I am just logging a message inside the method.

When I build the projects, I will have two dlls, StartupHook1 and StartupHook2.

Now take an existing .NET Core 2.2 application. For the demo, let’s just create an ASP.NET Core 2.2 Web Application. And to link the web application and the two class libraries (which are startup hooks), we need to add an environment variable named DOTNET_STARTUP_HOOKS to the web application as follows. We can easily do that by going to web application project properties and adding an environment variable.

image
ENVIRONMENT VARIABLE
It’s basically something like below.
DOTNET_STARTUP_HOOKS=SomePath\StartupHook1.dll;SomePath\StartupHook2.dll
Now I will just modify the web applications Main method to add some logging.
public static void Main(string[] args)
{
    Debug.WriteLine("Main is called.");
 
    CreateWebHostBuilder(args).Build().Run();
}

Now if I run the ASP.NET Core web application, I am seeing the below.

image
Debug Output
You can see that the Initialize methods in both StartupHook1 and StartupHook2 has been called before the actual entry point. And the execution order is the order we have defined the hooks in the environment variable.

Isn’t it nice.

For more information,
   Host startup hook

Happy Coding.

Regards,
Jaliya

Saturday, December 8, 2018

C# 8.0: Nullable Reference Types

Past week has been amazing, there were a lot of new announcements at Microsoft Connect(); 2018. Two of them are the first previews of both Visual Studio 2019 and .NET Core 3.0 (Visual Studio 16.0.0 Preview 1.0 and .NET Core 3.0.0 Preview 1).

And with these, we get the opportunity to try out some of the features which will be coming in C# 8.0. In this post, let’s go through Nullable Reference Types which is one of them.

Without explaining the feature, let’s consider the following code.
class Program
{
    static void Main(string[] args)
    {
        Employee employee = null;
        Console.WriteLine(employee.Name);
    }
}
 
class Employee
{
    public string Name { get; set; }
}
The code is pretty obvious, you can see that when the employee is null, trying to access its property Name will throw a NullReferenceException.

Now closely look at the following two pictures. First one is when we are on C# 7.3 (Visual Studio 15.9.3) and the second one is when we are on C# 8.0 (Visual Studio 16.0.0 Preview 1.0). If you are wondering how to select language version in Visual Studio, check out this post
image
C# 7.3 (Visual Studio 15.9.3)
image
C# 8.0 (Visual Studio 16.0.0 Preview 1.0)
I am sure you can spot the difference. Visual Studio is not issueing any warnings in the first picture, but in the second, Visual Studio is issuing a couple of warnings.

This is because C# 8.0 is introducing nullable reference types and non-nullable reference types. So starting with C# 8.0, all the reference type variables are not nullable and if the compiler sees a code trying to dereference a non-nullable reference type, it will issue a warning. But as of now, you are opted-out for this feature by default. You can opt-in to this feature (which is known as nullable contexts) using the following two approaches.
  • Project Wide:
This is by adding the following line to the .csproj file right after the LanguageVersion.
<NullableReferenceTypes>true</NullableReferenceTypes>
  • Using a newly introduced pragma, #nullable.
#nullable enable
#nullable disable
I am using project-wide setting for the post here.

Now if we have a look at the warnings Visual Studio complains about, it has three warnings.

CS8600: Converting null literal or possible null value to non-nullable type.

This is because our the variable employee of type Employee is no longer nullable. If we expect the variable to be nullable, we can change the variable initialization as follows (just as we will do for values types).
Employee? employee = null;
And prior to C# 8.0 this wasn’t possible.

CS8602: Possible dereference of a null reference.

Since our employee variable can be null, we need to update the code to add null conditional operator which got introduced with C# 6.
Console.WriteLine(employee?.Name);
CS8618: Non-nullable property 'Name' is uninitialized.

This is a nice one. Name property of Employee is a type of string and string is a reference type. Now in our sample, employee is null meaning that a value for Name is not set. To fix this we can update the code as follows.
public string? Name { get; set; }
And again this wasn’t possible prior to C# 8.0.

null-forgiving operator (!.)

This is another feature which is part of nullable reference types. Consider the below code.
class Program
{
    static void Main(string[] args)
    {
        Employee? employee = null;
        // some code
        Console.WriteLine(employee.Name);
    }
}
 
class Employee
{
    public string? Name { get; set; }
}
This will again issue us “CS8602: Possible dereference of a null reference”. If we know employee is not going to be null because of some code, we can override the warning by updating the code as below.
Console.WriteLine(employee!.Name);
I am sure nullable reference types will tremendously help us in writing quality code.

Happy Coding.

Regards,
Jaliya