Monday, May 28, 2012

Improvements in C# 4.0

Improvements in C# 4.0


C# in .NET Framework 4.0 has some more things to offer. These are:
  • Dynamic lookup
  • Named
  • Optional parameters

Dynamic Lookup

There is a new static type named dynamic. We can use it as object of any type. If there is any error on its usage, we would get it on runtime only. For example:
dynamic integerValue = 1; 
dynamic stringValue = " a string"; 
dynamic Result = integerValue + stringValue;
Output of this would be: 1 a string.
But, if you change the last line to:
dynamic Result = integerValue & stringValue;
You will not get any compilation error, but the following error on runtime:
Operator '&' cannot be applied to operands of type 'int' and 'string'

Optional Parameters

To implement optional parameters, we used to create overloaded functions before ASP.NET 4, but now, optional parameters are no more a restriction in C#. Like VB, optional parameters must be mentioned last. For example:
public void FunctionOptionalParam(string Name, int Age, string Country = "") 
and we can call them without mentioning the value for the optional parameter.
FunctionOptionalParam("My Full Name",20);

Named Parameters

Named parameters allow you to ignore the parameter order and mention parameters with names in a different order. For example:
public void FunctionNamedParam(int x, int y , int z)
On function call, it would be:
FunctionNamedParam(x:1, z:3, y:2);
Although we are sending a value for the parameter z before its order in the function declaration, but these would be equal to x=1, y=2, z=3.

0 comments:

Popular Posts

Recent Posts

Unordered List

Text Widget

Blog Archive