Using C# 6 in ASP.NET 5

Introduction and Background

Previously on my blog, I had talked about the new features of C# 6, I discussed many things about those features as well as I talked about whether those features are “actually” new of just sugar coats. Anyways, no disrespect to the hard work team had put forth in implementing those features and I personally like most of those features. For those of you who are interested in reading that post of mine, please redirect here: Experimenting with C# 6’s new features. I hope you will like the post and consider it to be worth sharing.

In this post, I am going to talk about using those features in ASP.NET 5! I think, this would be my last post about ASP.NET 5, because later I would be talking about ASP.NET Core 1.0 which was introduced as the new name for the technologies from now on. Anyways, until then I am going to use ASP.NET 5 terminology and I will explain how you can use C# 6 features in your ASP.NET 5 applications, to make the processes even better, performance efficient and more readable if you are a team of programmers working together to bring a major project.

So basically, what you are going to learn in this post is:
  1. ASP.NET 5: Not very basics, but enough to allow beginners to understand.
  2. C# 6 features: They have already been discussed, so please read the previous post.
  3. How to improve performance of your web application!
This is another major post of mine, comprising of both ASP.NET and C# topics. Typically, I will use ASP.NET more than I am going to talk about C# itself so that web developers can gain some benefit from this post of mine. So let’s get started.

Using C# 6 features in ASP.NET

What we have in ASP.NET is just a framework used for building web applications. C# is just the language that we can use to program the applications. However, the smoother, efficient and efficient the programs there would be, the better your web applications would perform. C# 6 is the latest version of C# programming language and would definitely use Roslyn compiler. You can use this language in your previous versions of ASP.NET, like ASP.NET 4.5. But for the sake of this post, I am going to use

ASP.NET 5!

ASP.NET 5 itself is very fine tuned… But using the power of C# 6, you can make it even better. In this post, I am going to show you a few methods that you can use C# 6 in. I will start in the similar manner that we had previously (in the previous post) and I will explain the code usage in the terms of ASP.NET web application development scenarios, instead of simple C# programming.

String interpolation

Personally, I am a huge fan of this feature because I have waited for this feature for a very long time. I have always been using string.Format function or StringBuilder objects to generate the strings, but using this feature I can easily write the messages that I want to write.

Now, when you are going to write the strings using dynamic data from the users. I would recommend that you write them using the string interpolation. Like this,
  1. var message = $"Hello {Username}, you have {count} unread messages.";  
  2.   
  3. // Then you can use this value in views, or back-end model management, or in HTML  
  4. <p>@message</p>  
This way, you won’t have to generate the string representations using concatenations, or to create the string builders. I have already demonstrated that this method is similar to what we had as String.Format() function! Only that this method is much better. A real world example of this usage is, that ASP.NET provides interfaces that you can use to trigger SMS and Email notifications. While previously you had to write the following code:
  1. var message = string.Format("Hello, {0}! Use {1} as your code to activate the service.", username, token);  
  2.   
  3. // Send the code through SMS or email services  
Basically, that is a good approach, mostly developers use concatenation. Which is a really very bad approach to build strings. Instead now you can do the following:
  1. var message = $"Hello {username}! Use {token} as your code to activate the service";  
This is a really very short way of building the strings, and guess what? They always translate down to string.Format function calls. :-)
Conditional try…catch

Now, I have been mostly watching the source codes of programmers to be like:
  1. try  
  2. {  
  3.     // Code that may raise exception.  
  4. catch (Exception er)   
  5. {  
  6.     if (er is NullReferenceException)  
  7.     {  
  8.         // Log this null error  
  9.     } else   
  10.     {  
  11.         // Chain the exceptions or just leave...  
  12.     }  
  13. }  
What this is, that it would always enter the catch block. Then, inside that block you would be checking the condition that you want to check. So, in C# 6, you can make it even more readable. You can change that code to be like this:
  1. try  
  2. {  
  3.     // Code that may raise exception.  
  4. catch (Exception e) when(e is NullReferenceException)  
  5. {  
  6.     // Execute this block in case the error was "null" reference.  
  7. catch (Exception e) when(e is UnauthorizedAccessException)  
  8. {  
  9.     // Execute this in case the exception was this one..  
  10. }  
  11.   
  12. // You can chain the exception conditions...  
This way, you can allow the exception to propagate back if you are not interested in logging the error on your end. The condition would be checked against, and then it would continue to next statement if the condition is not met.

name of operator

In ASP.NET environment, I think this variable would have the most use! How? Most of the times, developers have to “guess” the variable and then write its own “hardcoded” name. For example like this,
  1. string name = null;  
  2.   
  3. // Now when you will call any function on name,  
  4. // it would raise exception. Like:  
  5. int length = name.Length;  
  6.   
  7. // Before C# 6, you would do:  
  8. // inside catch block  
  9. var message = "Sorry, name was null.";  
That is OK! There is no problem with this one… But, what if you later refactor your code and change the name of that variable? Even if the changes are not going to be reflected on the production environment, you are still going to use the details on your development environment. So what you would have to do is that you would have to change these string literals too, just to depict the changes in the system.

Well, C# 6 got you covered for that. You can now know which variable was the problem in your code.
  1. string name = null;  
  2.   
  3. int length = name.Length;  
  4.   
  5. var message = $ "Sorry, {nameof(name)} is null.";  
That is same to what we had previously, but what is difference? The difference is that now you will be able to refactor the variable. By refactoring, previously, you would have to edit the strings too, instead in this method, while refactoring the variable names would be updated throughout and nameof() operator would return the “current” name of that variable! Also, if you were making a model and then rendering it…
  1. class Model  
  2. {  
  3.     public string Name   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Email  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13. }  
  14.   
  15. // You could do this:  
  16. var message = $ "{nameof(Email)}: {Name}, {nameof(Email)}: {Email}";  
Fully using the power of C# 6!

Null conditional operator

What I have seen in most of the cases, in my experience is that beginners typically get stuck at “NullReferenceException”! Anyways, what I think is that this error is very helpful in many cases and I suggest that you become a friend with this error, as it can be really very helpful in many cases. (Which cases? That requires a separate article post!)

You can then basically minimize the error if the error is to be null reference object. To do that you just append “?” to the variable name, and if that object is null at the time of execution, C# won’t throw an exception instead it would store null in turn.
  1. string message = null;  
  2.   
  3. var length = message?.Length;  
In the previous case, it would throw an exception. However, in this case there won’t be any exception. But there is another “exception” to this use. I have already talked about that exception, the thing is… Your “length” variable is now also null, so if you would try to use that variable, it would then raise another error unless you use the same condition to override it.

I recommend that you read the same section in my previous post, and see how this operator “is” useful and how this operator “is not” useful at all.

Auto-properties

In ASP.NET, Models are typically just structures. You don’t have any default value in them, but if you would want to design your structures to hold a default value that you want to display when user is opening the form. You can do so like this:
  1. class SomeForm  
  2. {  
  3.     public string Name   
  4.     {  
  5.         get;  
  6.         set;  
  7.     } = "Your name.";  
  8.     public string Email   
  9.     {  
  10.         get;  
  11.         set;  
  12.     } = "[email protected]";  
  13.     public string Message   
  14.     {  
  15.         get;  
  16.         set;  
  17.     } = "Enter your message here.";  
  18. }  
When you would now render these as form elements, you are going to get these by default. You usually enter these in the HTML, hardcoded form. Instead, using this approach you can get a consistent and dissected environment in which you can later focus on the model itself, later.

You can also use the same for getter-only properties. The getter-only (or readonly) fields can also be initialized in the same manner:
  1. public Helpers  
  2. {  
  3.     public static string SMTP   
  4.     {  
  5.         get;  
  6.     } = "smtp.example.com";  
  7. }  
This would allow you to manage the value in this one line itself, instead of using a constructor to initialize it with a value.

Lambda use in ASP.NET

If not string interpolation, then I am a huge fan of lambda expressions! These expressions come from the realm of functional programming. The benefit of them is that they don’t have any side-effects. By that, I mean that the function is just the evaluation of the values and then the values are returned instead of having a stack created for the function itself.
  1. public int Multiply(int a, int b)  
  2. {  
  3.     return a * b;  
  4. }  
This can be minimized to the following code,
  1. public int Multiply (int b, int b) => a * b;  
There are two benefits to having this.
  1. The code looks more readable.

  2. There is no more stack!
The code is evaluated and the value is returned.
 
So not just this improves the code readability, it also improves the performance of the code! You can try that out, and just to see the working, you should read the previous post.

Another good use of lambdas is in getter-only auto-properties! Old versions of the properties always relied on a backing field. These fields were then called to provide or set the values. However, that caused an extra call to be raised to the backing field. What lambda expressions have is that you can write a field like a lambda, just as we know that lambda expressions don’t work around with other fields, this way… The lambdas would help us to develop readonly fields in a much better way.
 
So, for example, if you create a property like this:
  1. public string Name { get; } = "Afzaal Ahmad Zeeshan";  
What this is going to do is that it would create a backing field, then this value would be stored to that backing field. In turn, whenever you would call this property, it would then call the backing field to get that value. Another call would be made.

Instead, using lambda expressions you can do this:
  1. public string Name => "Afzaal Ahmad Zeeshan";  
What this has as a benefit is that,
  1. Since this is a readonly property:

    • You are not going to update it later.
    • You provide a default value in this.
    • It acts just like a constant field.
    • No overhead calls.

  2. More readable code!
Lambdas not just make your functions better, it also makes your (readonly) properties better! Technically, you can improve the performance of your applications.
Points of Interest

I have not yet covered all of the features that C# 6 introduced, why? Because most of them are not going to be used by “average” developers and only a number of people would be using them. A few of such cases is,
  1. Index initialization in the dictionary.
  2. Parameterless constructor of struct type.
  3. So on…
However, this post would help you to understand the use of C# 6 features in ASP.NET web applications. You have already read that not just this improves the syntax, instead it also makes the application perform much better.

I would personally recommend the following uses to be made “must have” in your web applications:
  1. String interpolation

    • Makes your string much more readable.
    • String template can be edited easily.
    • Translates to the better method of generating the strings.

  2. Lambda expressions

    • You have read that lambda expressions make your functions more efficient.
    • The getter-only auto-properties are more like constant fields.
    • Auto-properties are much more readable.
These were a few of the tips that I wanted to give to those ASP.NET web developers who are going to use Roslyn compiler and are going to make use of C# 6 language. If you are into C# 6, I “recommend” that you make use of these cool features.

Later, I will share some more of the same tips and recommendations, once I have finished recording them for you.

Up Next
    Ebook Download
    View all
    Learn
    View all