Read, With the Name of Your Lord Who Created

C# 3.0: Inferred Type Variables, Extension Methods, and Lambda Expressions

Posted by triaslama on May 27, 2008

C# 3.0 brings many of new features. Some of features developed from the existing one (such as lambda expressions that provides more concise syntax than anonymous methods). Other features can be considered as totally new (such as LINQ). In this post together we will learn about Inferred type variables, extension methods, and lambda expressions.

By reading this article I assume that you are familiar with C#, knowing the previous features of this language is a plus.

Inferred Type Variable
Inferred type variable presented through ‘var’ keyword. If you are a Javascript programmer you must be already familiar with ‘var’ keyword. But, ‘var’ in C# 3.0 has different meaning with ‘var’ keyword in Javascript. In C# 3.0 when we use ‘var’, we tell the compiler that the type of variable should be inferred from the assignment. In Javascript var means that a variable can hold any kind of type.
Consider the following Javascript file:

    var myVariable = 5;
    window.alert(myVariable);
    myVariable = “I change the type of myVariable, now myVariable is a string!”;
    window.alert(myVariable);

 

At the beginning I assign myVariable with 5 (an integer), but later, I assign myVariable with a string (so myVariable can hold any kind of value). But its not the case with ‘var’ in C# 3.0.

using System;

class InferredTypeVar
{
   static void Main()
   {
      var myVariable = 12.5;
      Console.WriteLine("myVariable: "+myVariable);
   }
}

 

Because I assign 12.5 to myVariable then type of myVariable will be double. If we try to fake the compiler and add the following code (hoping that it will the same as in Javascript):

myVariable = "I try to change the type of 'myVariable' to 'string' data type.";

Re-compile the program and a compile time error will be generated by compiler. I compile it with Mono 1.9 and I get the following error:
Cannot implicitly convert type `string’ to `double’

Extension Methods
Extension methods is a way to extend the functionality of existing types by defining static methods that are invoked using instance methods syntax. Extension methods must be marked as static and defined inside a static class. An extension method is declared by specifiying ‘this’ keyword on the first parameter of the method.
Lets try and hope we will find interesting stuffs!

using System;

namespace LearningNewFeatures
{
	public static class ExtensionClass
	{
		public static string Reverse(this string str)
		{
			string result = string.Empty;
			for (var i=str.Length-1;i>=0;i--) {
				result += str[i];
			}

			return result;
		}
	}

	class TestApp
	{
		static void Main()
		{
			var words = new string[]{"the words", "we could't say", "easily"};

			foreach (var word in words) {
				Console.WriteLine(word.Reverse());
			}
		}
	}
}

 

Compile the above program, and you should get the following result:
sdrow eht
yas t’dluoc ew
ylisae

Now, you can see that I put the ‘this’ keyword as the first parameter of Reverse method (and the only one parameter). Then look at TestApp class, I have array of string and I call the Reverse method as a method of string class!
Not only that, I call Reverse method with instance method syntax although it defined as static in a static class. One more thing, because Reverse become a method of string class we not anymore pass a parameter when we call it!

To better understanding on extension methods maybe we need one more example, and here is:

using System;

namespace LearningNewFeatures
{
	public static class ExtensionClass
	{
		public static int Multiplication(this int a, int b)
		{
			return a*b;
		}
	}

	class TestApp
	{
		static void Main()
		{
			var numbers = new int[]{13, 15, 20, 25};

			foreach (var number in numbers) {
				Console.WriteLine(number.Multiplication(10));
			}
		}
	}
}

 

And I get the following result for above program:
130
150
200
250

In this example we have an extension method (Multiplication method) with two parameters, both has int data type. Now Multiplication will be a part of integer class. So when we have an integer variable named ‘number’ we can do this:
number.Multiplication(10);

Also notice that Multiplication method only receives one parameter although we defined two. Because the first parameter is the integer itself!

Lambda Expressions
Lambda expressions provides more concise, functional programming syntax for writing anonymous methods. Lambda expressions written with the following form:
parameter_list => expression
Consider that we want convert a string to upper case. This is the way we use when we work with anonymous methods:

using System;

namespace LearningNewFeatures
{
	public delegate string ConvertToUpperCase(string input);

	public class AnonimMethodTest2
	{
		static void Main()
		{
			ConvertToUpperCase handler = delegate(string str)
			{
				return str.ToUpper();
			};

			Console.WriteLine("Nitty gritty hello world => "
                               +handler("Nitty gritty hello world"));
		}
	}
}

 

This is the way when we do the same task using lambda expressions:

using System;

namespace LearningNewFeatures
{
	public delegate string ConvertToUpperCase(string input);

	public class LambdaExp
	{
		static void Main()
		{
		      ConvertToUpperCase handler = strInput=>strInput.ToUpper();

		     Console.WriteLine("lambda expressions => "
                         +handler("lambda expressions"));
		}
	}
}

 

Compile and run the program. This is the result for the last program:
lambda expressions => LAMBDA EXPRESSIONS

5 Responses to “C# 3.0: Inferred Type Variables, Extension Methods, and Lambda Expressions”

  1. Andra said

    saya mau tanya nih tapi OOT,
    gimana cara lu bikin kotaknya untuk nampung C# code ? rapi bener..

  2. triaslama said

    Caranya sederhana kok. Kita bikin elemen ‘div’ di bagian HTML view, terus code kita ditaruh di dalam ‘div’ tersebut.
    Setelah itu kita tentuin style ‘div’ nya (misalnya untuk background color, border, font, dsb.).
    Untuk mengatur tabulasi kadang bisa juga pake ‘pre’ element.

  3. The C# team amazes me by not being conservative and bringing this language to the realm of dynamic and functional programming.

    Thanks a lot for the article. As someone who also code some JavaScript, I particularly like your enlightening comparison of JavaScript and C#’s var.

  4. triaslama said

    Yes I am agree that C# now brings many good stuffs for us!

  5. Cheap Pharmacy – Ortho Evra…

    C# 3.0 brings many of new features. Some of features developed from the existing one such as lambda […]…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: