C# 4.0

Lets move to C# 4.0

Posted on Updated on

Some features like Dynamic programming,Optional arguments,Named arguments

Dynamic Programming :

This is the major feature of C# 4.0. In the first look it looks something like our previous “var” type of C#3.0 or regular object type that we have with C#,root Type of .NET . But its not like that. Actually when you assigns a variable of Type “dynamic” and use its properties/methods ,compiler doesn’t mind it at compile time. Means, no method/property resolution takes part in compile time and it will take care all of those things at run time. By these words dont think “dynamic” is dynamic type ,its a static type only.

The below mentioned code is a small example for the dynamic programming.

using System;
using System.Text;

namespace DynamicType
	class Program
		static void Main(string[] args)

			Mathematics objmathematics = new Mathematics();
			dynamic objdynamic = objmathematics;

			double resAdd= objdynamic.add(3,2);

			//The method "subtract" is not present in the Class Mathematics.
			double resSub = objdynamic.subtract(3, 2);


	class Mathematics
		public Mathematics()	{}

		public double add(double a, double b)
			return a + b;		

On compiling the above code, the build will succeed with a smile. But at run time it will break at code line number 18. Because the function “subtract” that is trying to resolve is not present in the Mathematics Class and method “add” will pass through because it is available.

The DLR, Dynamic Language Runtime is responsible for this dynamic programming capability . Basically its built on the top of the CLR to make the dynamic languages such as IronPython, IronRuby etc to get supported. To know more about DLR please go to this link

The main use of this dynamic programming is to support the compilation during interfacing of our managed code with COM , Javascript DOM or any dynamic languages.

Optional and Named arguments:

Now we can have optional values for the C# methods . We can set default values for the arguments and can pass the values during the method call according to our need.Also we can call each parameter by its name , not by its position as earlier. This is called Named argument

It will be like this :

public double GetPNRValue(double a=1,double b=0,double c=1)
			return (a * b / c);

And when we call this method, we can pass arguments like this

double resPNR = objdynamic.GetPNRValue(2,c:0);			

It says that “a” is 2, “b” can be the optional argument and “c” be zero . Here “c” is the Named argument.