What’s new in C# 6?

Even though I’m still using VS2013 for all the projects I’m working on, it won’t hurt to know the new features of C# 6 in VS2015.  I might start converting some of them or maybe start the new projects in VS2015, who knows.

I won’t try to write about the new features in C# 6 in this post as I am pretty sure you can find them on the Internet.  Though there is one that I like and it’s New Language Features in C# 6.  I hope this helps.

C#: Using or not using

I am not referring to the using directive to import types defined in other namespaces, but I am referring to the using statement to define a scope where at the end of it an object will be disposed, such as this:

using (var cn = new SqlConnection())
{
	// your code here...
}

 

Just be aware that the using statement is just a shortcut or a convenient syntax for the below code:

var cn = new SqlConnection();
try
{
	// your code here...
}
finally
{
	if (cn != null) ((IDisposable)cn).Dispose();
}

 

And if you have a trycatch block in your method, either outside or inside the using statement, or maybe even both, then you need to make sure the flow of control and the logic when an exception occurs is what you would expect, because nested trycatch block can become confusing.  Just remember the using statement is a tryfinally block.

My point is, don’t haphazardly use using statement especially if you are using it for several objects in your method, because depending on what you are trying to achieve, sometimes its better to just use a complete trycatchfinally block to make your code simpler to understand.

EDIT:

Rule of thumb is if the resource object you are trying to use in your method needs to be disposed of by your method then using statement is best.  And make sure you are instantiating the resource object inside the using statement and not outside and passing the variable to it.  See using Statement (C# Reference).

Why I Chose C# Over VB.NET?

It’s a no brainer really.  So I can easily switch between the programming languages that are widely used now in web (i.e. JavaScript) and mobile applications (i.e. Java and Objective-C) and in the future (i.e. TypeScript and Dart).  Note that this is coming from someone who develops in the Microsoft stack.

I don’t know about you, but whenever I switch between C# and VB.NET (at one point I was maintaining desktop applications written in both languages), I always get hit by a brick wall when I go over a VB.NET code, it’s like my fingers are all numb?  I guess if you are working on desktop applications only, it does not matter which language you use.  But nowadays, developer needs to be versatile and be able to work on web applications too, and if you’re lucky enough, on mobile applications as well.

And you know what?  New languages are being created based on the  C programming language, which is where C# is based from by the way.  You might have known about the new language developed by Microsoft, the TypeScript.  And there is Dart from Google as well.

So I say, you wouldn’t go wrong if you go the C# way.  And that’s why I now prefer C# over VB.NET.

C#: What’s with Enums anyways?

c#snow1

Well, I’ll tell you.  You can define your own strings with Enums using reflection.  You can also use the type-safe-enum pattern if reflection seems slow to you.  And do you know you can use Enums to represent bit flags?

Associating Enums with strings in C# shows you how to define your own strings with Enums using reflection.  For type-safe-enum pattern implementation, check it out hereThe ins and outs of C# enums shows you how to use Enums to represent bit flags.

C#: Does the code below look familiar?

extmethod

If not or you are struggling to understand it, then no worries.  I too didn’t understand it fully well when I coded this, but it worked wonderfully.  I am going to break down this code into digestible parts because there is just too much.  I would suggest going through the provided links as well to fully understand each part before going to the next.

In the code, I am declaring a new extension method, named OrderByWithDirection, to be used as a LINQ query operation to sort elements in either ascending or descending order.  See Standard Query Operators Overview.  In LINQ query, you have separate methods for sorting in ascending order, the OrderBy , and sorting in descending order, the OrderByDescending.  OrderByWithDirection can do both ways, so I am passing a sort direction in the third parameter:

    public static IOrderedQueryable<TSource> 
		OrderByWithDirection<TSource, TKey>(
			this IQueryable<TSource> query, 
			Expression<Func<TSource, TKey>> keySelector, 
			string sortDir)

 

So what’s an extension method?  An extension method is like a static function that you can add to an existing type so you can call it from any instance of that (extended) type.  See Extension Methods and How to: Implement and Call a Custom Extension Method.  In the code, I am making OrderByWithDirection available to any data structures that implement IQueryable<TSource>, which is why the first parameter to this method is of that type:

    public static IOrderedQueryable<TSource> 
		OrderByWithDirection<TSource, TKey>(
			this IQueryable<TSource> query, 
			Expression<Func<TSource, TKey>> keySelector, 
			string sortDir)

 

Depending on the sort direction, OrderByWithDirection calls either OrderBy or OrderByDescending, both of which are actually extension methods themselves extending IQueryable<TSource>.  So it’s only logical that OrderByWithDirection extends the same type as well.  OrderBy and OrderByDescending are part of the Queryable class, much like OrderByWithDirection is part of ExtensionMethods class in the code.  See Queryable Class, Queryable.OrderBy Method, and Queryable.OrderByDescending Method.

OrderBy and OrderByDescending requires an Expression<Func<TSource, TKey>>, basically a function to extract a key from an element.  So in OrderByWithDirection, I am passing this function on the second parameter:

    public static IOrderedQueryable<TSource> 
		OrderByWithDirection<TSource, TKey>(
			this IQueryable<TSource> query, 
			Expression<Func<TSource, TKey>> keySelector, 
			string sortDir)

 

To call OrderByWithDirection you would code something like this:

// products variable is of type IQueryable<Product>
products = products.OrderByWithDirection(p => p.ProductName, "desc");

 

Here we are passing a lambda expression.  At first, it might look like this lambda expression is returning the product name value and not the product name key, ProductName.  But because we are passing this as an Expression<Func<TSource, TKey>>, the lambda expression is being represented as an expression tree which makes this possible.  See Expression<TDelegate> Class, Func<T, TResult> Delegate, Expression Trees, and How to: Use Expression Trees to Build Dynamic Queries.

Last but not the least, the return type.  Since OrderByWithDirection returns whatever the OrderBy or OrderByDescending returns, it’s only logical to return the same type as well, which is IOrderedQueryable<TSource>. See IOrderedQueryable Interface.

Below is the complete code in text:

using System;
using System.Linq;
using System.Linq.Expressions;

public static class ExtensionMethods
{
    public static IOrderedQueryable<TSource> 
		OrderByWithDirection<TSource, TKey>(
			this IQueryable<TSource> query, 
			Expression<Func<TSource, TKey>> keySelector, 
			string sortDir)
    {
        if (sortDir.ToUpper().Equals("DESC"))
        {
            return query.OrderByDescending(keySelector);
        }
        else
        {
            return query.OrderBy(keySelector);
        }
    }
}