Tuesday, January 20, 2015

Coalescing operator ?? in C#

?? operator in C# is a binary operator. It is also called as null coalescing operator, which returns the left hand operand if it has any value, else, returns the right hand operator. Confused, let's see an example for this.
Suppose we have a property UserId of type int and nullable in nature. While using this property, if it has any value i.e. Not Null, then use that value, else, use some other value. So first thing that comes to mind is use the if-else, something like below:

Null coalescing operator provides a very shorthand syntax for this, which changes the code to:

Easy and concise to use. Happy coding...!!!

Saturday, January 17, 2015

Var vs dynamic keywords in C#

Programming languages can be normally considered to be either statically typed or dynamically typed. A static (Not to be mixed with static keyword, used for classes) typed language validates the syntax or checks for any error during the compilation of the code. On the other hand, dynamically typed languages validate the syntax or checks for any error, only at the run time. For ex, C# & JAVA are a static type and javascript is dynamic type language.
C# was earlier considered as a statically typed language, as all the code written was validated at the compile time itself. But, with the introduction of the dynamic keyword in C# 4.0, it became a dynamic typed language also. The two concepts of static and dynamic types in C# can be illustrated with the use of two keywords named var and dynamic.  Let's discuss about some basic differences between these two, based on some of their characteristics.
1. When were they introduced :
  • var was introduced in C# 3.0
  • dynamic was introduced in C# 4.0
2. Type inference of variables :
  • var is a statically type variable. It results in a strongly typed variable i.e. the data type of these variables are inferred at compile time. This is done based on the type of value, with which these variables are initialized.
  • dynamic are dynamically typed variables. This means, their type is inferred at run-time and not the compile time in contrast to var type.
3. Initialization of variables :
  • var type of variables are required to be initialized at the time of declaration or else they run in compile time error as : Implicitly-typed local variables must be initialized.
  • dynamic type variables need not be initialized, when declared.
4. Changing type of value assigned:
  • var does not allows to change the type of value assigned, which is once assigned to it. This means, if we assign an integer value to a var, we cannot assign string value to it. This is because, on assigning the integer value, it will be treated as of integer type thereafter. So further any other type of value cannot be assigned. For ex, following code will give a compile time error

  • dynamic allows to change the type of value, assigned to it initially. In the above code, if we use dynamic instead of var, it will not only compile, but will also work at run-time. This is because, at run time, the value to the variable is first inferred as Int32 and when its value is changed, it is inferred as string type.

5. Intellisense help :
  • Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, compiler has all the information related the type. So we have the intellisense help available. See the code below. We have a var variable initialized with a string value. So its type is known to the compiler and we have the appropriate intellisense help available for it.

  • Intellisense help is not available for dynamic type of variables as their type is unknown till run time. So intellisense help is not available. Even you will be informed by compiler as - This operation will be resolved at run-time. See the code below :

6. Restrictions on the usage :
  • dynamic variables can be used to create properties and return values from a function.
  • var variables cannot be used for property or return value from a function. They can be only used as local variables in a function.
var vs dynamic vs object ?
If we closely observe dynamic type, it is performing pretty much the same task which the object type (which is the base type of all other types) does. Then what is the difference between object type and var then ? Also, why we need var when we have the object type. Let's discuss these points by doing some comparisons.
  1. While using object type, compiler provides only generic information, functionality or functions related to the type it holds, until it is being type cast into its actual type. This means, even if we have stored any integer or string values in an object type, we will get their related functions, only if we convert the object type into its actual type. See the code below :

Here, we only have generic properties and functions available for the type of value stored in it, which we will have, even if we store any integer or other type of value in it. Now, let's convert it to its actual type i.e. string.

Now after explicit conversion, we have the properties & functions specific to the string type. In case we use the var type to store the same value, we would not be required to do the explicit conversion, as compiler already infers its type from the value initialized and we will have its functions and properties.
2.  Based on the above point, object types increase the overhead of boxing and un-boxing, before we can use the actual values stored in it or use any function related to it. But this is not the case with var, as we already know its type at the time of use. For ex, in above code, we get to use the functions related to string only after we convert the object into string. So this results in un-boxing. On the other hand, for dynamic types, we only need to know that the function or property we are using, actually exists for the type of value being stored in it.

For example, in above code, if we know that dynamic variable will be storing string type, then we can use Length type property, even if it is not available in the intellisense help.
3. Next, we need to be careful while casting or converting the values, when using the dynamic or object type variables. Any wrong casting can result in run time errors. On the other hand, var type will give a compile time error with wrong conversion. So any run time error is not possible.

Here, object type stored string value, but we are trying to cast into integer type. So will throw run time error.

Similarly, we are storing back the string value, into integer type. So it would again result in error.
4.  In terms of interoperability with different frameworks, earlier we required object type to be used to get the underlying object type and then use reflection to access the related methods or functions. But with the introduction of dynamic keyword, we only need to know that a function or property exists on the underlying object and rest we simply need to make a call to these properties or functions.
5. As per MSDN,  ".....As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time....".
From these points, we cannot conclude which specific type we should use. It all depends on requirements whether we should go for var or dynamic or object type.
So this was all about the basic differences between var and dynamic keywords. Hope you enjoyed reading it...!!!

Saturday, January 3, 2015

Route and Route prefix - Web API 2

Web api is the buzz in the market these days for providing rest based api's. After its first release, further versions have been released, with version 2 being the one with some of the major changes. One of the very good feature introduced was the use of Attribute based routing of the web api requests. There were other feature also, but this feature is very big and useful in itself and our discussion will be for this only, in this article. Also, this article has its reference from a great write-up on this feature by Mike Wasson, here, which explains these features.
If you have worked with initial version webapi, you must be aware of concept of routing templates for the api controllers. But in its version 2, instead of defining routing templates in WebApiConfig.cs, we can define these templates at the method level i.e. on the methods of the web api controllers. This is possible through the use of the Route and RoutePrefix attributes, added to the webapi2. This does not means that we cannot use the routing template with convention of first release of webapi along with this. Both can be used side by side. So let's discuss these.
Initial Code setup:
1. Create a new MVC web application, with web api template.
2. Add reference to the
 webapi2 libraries, using the nuget package.
3. Add the
 Postman google chrome extension (Instead of making any html or mvc page, we will be using this extension, to make the test requests to the web api)
4. In our default values controller added, clear all the methods, add a 
Employee class and a method to return list of employees. So our api controller will look like the following:

Next, open the WebApiConfig.cs file, remove the default routing templates and simply add   config.MapHttpAttributeRoutes() to enable the attribute based routing.

Run the application. As the application is started, it will also cause hosting of the web api on the same development server. Now start the Postman extension and add the web-api url with method name, to which we want to make REST based calls. Click Send and see the results we receive:

This is the result which was expected.
Route Prefix in Web API
Now, suppose we add another method to it with Route attribute as FindEmployee and we need both the methods to have a common prefix in the api request url, say Employee. So instead of adding this as prefix to Route attribute of both these methods, we add a common attribute at the class level, called RoutePrefix and set its value to required prefix i.e.Employee.  So our code now changes to:

Now, we can make request to both the controller methods with the same prefix
 Employee. See the requests below:

Override Route Prefix
Next we have a situation where we do not our second method to use the same prefix as the first method. One solution could be use of a separate api controller and add the method to it. But this is not a good solution as you may required to add more methods in future, which do not use this prefix. To achieve this, we have the option to prefix the Route attribute value with a tilde(~) sign at the method level, for which we do not want to have the common prefix. So we add the tilde sign to the second method and make a direct call to the method. See the code below:

Now let's send the request with the changed url's and see the results.

Passing parameters in GET request
Now, let's see how we can send parameters to the request url. For this, we will be required to change the Route template and add a placeholder in it, which will be replaced by the parameter from the GET request.

Now, let's send the request and debug the code:

Bingo, we get the parameter in the code. We can also have a template, where the parameter placeholder is in between the url. So we can defined the Route template something like
Let's change our url and send the request again.

That look's great. This means we can name our url's differently and hide the actual method names from the client code.
Constraints on URL parameters
We can even restrict the template placeholder to the type of parameter it can have. For ex, we can restrict that the request will be only served if the eid is greater than 10. Otherwise the request will not work. For this, we will apply multiple constraints in the same request:
1. Type of the parameter eid must be an integer
 eid should be greater than 10
Let's see how we can do this.

Simply specify the type along with the placeholder, separated by a colon(:). Now try to send the request with a value less than 10 and we get the 404 error.

Change the value to greater than equal to 10 and it starts working again.
Optional and Default parameters 
I was really about to end the discussion until I came to knew about it's another great feature, using the optional parameters. But in this case, it becomes necessary to provide a default value to that parameter, in the method definition itself. For using optional parameters, we use the question mark(?) symbol to denote that it is an optional parameter. Let's see how we can have optional parameters:

 So these were some of the great sub-features of the Route and RoutePrefix feature in web api2. Let's summarize the features we discussed:
1. We have the Route attribute at the method level, to define routing templates.
2. We can define a common prefix for all the methods of the api controller, using
 RoutePrefix attribute.
3. We can override the RoutePrefix on a method, using the
 tilde(~) sign.
4. We can easily define parameterized templates in the attribute based routing
5. We can have parameters defined in-between the api request url
6. We can add certain constraints on the url parameters, i.e. their type or the values they can have, within the template itself.
7.  We can also have optional parameters in the methods, but with the condition that they must have a default value assigned to them.
So this was about the use of the Route and RoutePrefix attributes in webapi2. Sample code is attached with this discussion. Hope you enjoyed reading it. Happy coding...!!!