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
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.
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 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!
Compile the above program, and you should get the following result:
yas t’dluoc ew
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:
And I get the following result for above program:
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:
Also notice that Multiplication method only receives one parameter although we defined two. Because the first parameter is the integer itself!
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:
This is the way when we do the same task using lambda expressions:
Compile and run the program. This is the result for the last program:
lambda expressions => LAMBDA EXPRESSIONS