- Object & Collection Initializers
- Implicitly Typed Variables
- Anonymous Types
- Extension Methods
- Expression Trees
- Lambda Expressions
Lambda Expressions:
Lambda Expressions are, simply put, functions and methods. They can contain expressions and statements, and can be used to create delegates or expressions tree types. Lambda Expressions use the => token. This operator allows us to write anonymous inline functions that look much cleaner. The Lambda Operator is used extensively in LINQ. Not only can make out code much cleaner, and in most cases more efficient. Now lets take a look at how the Lambda Operator:
Without the Lambda Expression
class Class1
{
delegate void DoSomethingDelegate();
public void InvokeMethod()
{
DoSomethingDelegate del = new DoSomethingDelegate(SampleMethod);
del();
}
void SampleMethod()
{
Console.WriteLine("Do Something Here");
}
}
With the => token (using the Lambda Expression:
class Class1
{
delegate void DoSomethingDelegate();
public void InvokeMethod()
{
DoSomethingDelegate del = () => Console.WriteLine("Do Something Here") ;
del();
}
}
Notice how much cleaner that code is using the Lambda Expression. It reduced our code from 11 lines to 7 lines total (including the class signature).
Implicitly Typed Variables:
With this new feature a variable can be inferred a data type using the new var keyword. This new keyword are implicitly typed. This keyword is also used extensively in LINQ. Here is an example f how the var keyword works. In 2.0 you declared a variable like this
int i = 0;
With this new keyword variables can be implicitly typed, like so
var i = 0
The compiler automatically knows that i is of the int data type.
Anonymous Types:
Anonymouse Types are types (or properties of an object or class) automatically inferred (similar the Implicitly Typed variables) and are created by the object initializers. The object initializer specifies the values from one (or more) properties/fields from an object or class. Simply put you can specify a series or properties from an object or class from a series or assignments, such as
{ FirstName = "Richard", LastName = "Smith" }
Now your object or class is automatically given these properties. In layman's terms an Anonymous Type is a type that wasn't initially exist and wasn't defined in code. With the example above the compiler creates anonymous typeswith the properties inferred from the objects initializer, meaning the new class will have properties FirstName and LastName.
Remember, if you do not specify names with the anonymous types the compilers will give them members of the same name as the properties used to initialize them. Here's an example of this
var query =
from client in Clients
select new { client.FirstName, client.LastName };
foreach (var person in query)
{
Console.WriteLine("FirstName: {0}, LastName: {1}", v.FirstName, v.LastName);
}
Notice how the compiler gave FirstName and LastName to the person in the foreach loop.
Expression Trees:
Expression Trees give a way of translating executable code into some form of data. This act can be extremely valuable, especially if you want to modify code that is being executed. It can also be very useful if are wanting to transform or modify some LINQ query into code that operates in a different process, say a database.
They represent language-level code in the form of data, and that data is stored in a tree-shaped format, with each node representing an expression.One of the cool features of the Expression Tree is BuildString on your instance of the Expression Tree, which will retrieve the Lambda Expression of the delegate. Here is an example
Expression<Func<int,int,int>> exp = (x,y) => x / y; //first we invoke our delegate var original = exp.Compile(); var two = original.Invoke(10,5); //now we get the Lambda Expression from our expression string StringBuilder builder = new StringBuilder(); expression.BuildString(builder); // (x, y) => Divide(x, y) var lambda = builder.ToString(); // Get Parameters,we have 2 (x, y) var parameters = exp.Parameters
As you can see Express Trees, along with BuildString and the Lambda Expression can greatly improve and simplify our
code.
Extension Methods
Extension Methods are static methods that can be invoked using the instance method syntax. The main difference between Extension Methods and static methods are as follows:
- Extension Methods must have the this keyword as the first argument
- Extension methods can only be declare within static classes, no so with static methods
- The arguments declared in an Extension Method with the this is not passed when the Extension Method is consumed, with a static method no arguments are skipped and all arguments must be entered.
- Extension Methods can only be called on instance values
- Though Extension Methods are static, there can only be a single instance, otherwise you get a compilation error
public static void IsRequired<T>(this T obj, Expression<Func<T, bool>> p)
{
var requiredObj = pred.Compile();
if (!requiredObj(obj))
throw new Exception("Object Required: + p.ToString());
}
Object & Collection Initialerzs:
This new feature allows programmers to create objects and collections in an expression context rather than a statement context. This is referred to in-line initialization of objects.
Difference between Expression Context and Statement:
- Statement Context: Where the compiler expects and car then parse a statement.
- Expression Context: First it's much more limited, you can pass an expression to a method, but you're not allowed to write a complete statement where an argument is thus expected
public class Person
{
string _name;
int _age;
public Person(string name, int age)
{
_name = name;
_age = age
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
}
You can then initialze the class as such
Person person = new Person(name,age);
Now with 3.0 not only do you not need to create constructors for your class, you can simply initialze your Person class like so
Person person = new Person { Cat.Name = "Richard", Age = 40 };
So as you can it's much simpler and uses a lot less code. Now as you can image there are more additions to Framework 3.0, but in this I wanted to focus on the large ones that will make your life as a programmer much easier, and allow for faster deployment of applications. I hope you found this tutorial useful and informative, and thank you for reading.
Happy Coding!



MultiQuote




|