Labels

Showing posts with label Orcas - C# Features. Show all posts
Showing posts with label Orcas - C# Features. Show all posts

Tuesday, April 29, 2008

C# ?? null coalescing operator - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword

?? null coalescing operator

This provides a nice, terse way to check whether a value is null, and if so return an alternate value.

Simply put, the ?? operator checks whether the value provided on the left side of the expression is null, and if so it returns an alternate value indicated by the right side of the expression. If the value provided on the left side of the expression isn't null, then it returns the original value.

The ?? operator works for both reference types and value types.

String message = "Testing";

String result = message ?? "Null Value";

int? age = 55;

int retirement = age ?? 58;

Using the ?? operator with LINQ

Let's consider a scenario where we have an XML file or feed with the following contact data:

To handle such situation the use of ?? null operator comes in picture as below.

Reference: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx

Thanks & Regards,

Arun Manglick || Tech Lead

Var Keyword - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword


Var Keyword

"Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations.

For example, I could use the var keyword like below to declare three variables:

var name = "Arun";

var age = 30;

var male = true;

The compiler will infer the type of the "name", "age" and "male" variables based on the type of their initial assignment value (in this case a string, an integer, and a boolean). This means it will generate IL that is absolutely identical to the code below:

string name = "Arun";

int age = 30;

bool male = true;

A common misperception that people often have when first seeing the new var keyword is to think that it is a late-bound or un-typed variable reference (for example: a reference of type Object or a late-bound object like in Javascript). This is incorrect -- the var keyword always generates a strongly typed variable reference. Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.

The CLR actually never knows that the var keyword is being used - from its perspective there is absolutely no difference between the above two code examples. The first version is simply Syntactic Sugar provided by the compiler that saves the developer some keystrokes, and has the compiler do the work of inferring and declaring the type name.

The var keyword can be used to reference any type in C# - meaning it can be used with all three Explictly Declared Types [As above], Custom Types and Anonymous Types.

Explictly Declared Types: As Above.

Custom Types:

In addition to using built-in datatypes with the var keyword, you can obviously also use any Custom Types you define. For example, I could go back to the LINQ query projection, that uses an explicit "MyProduct" type for the data-shaping and adapt it to use the var keyword like so:

Anonymous Types:

Same as ‘Custom Types’ except when instantiating anonymous types you instead just leave the type-name blank after the "new" keyword:

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead

Collection Initializers - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword


Collection Initializers

Object Initializers are great, and make it much easier to concisely add objects to collections. For example, if I wanted to add three people to a generics-based List collection of type "Person", I could write the below code:

List<Person> people = new List<Person>();

people.Add(
new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 } );
people.Add(
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 } );
people.Add(
new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 } );

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what I'd need to type with the C# 2.0 compiler.

The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes:

List<Person> people = new List<Person> {
new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 },
new Person { FirstName = "Bill", LastName = "Gates", Age = 50 },
new Person { FirstName = "Susanne", LastName = "Guthrie", Age = 32 }
};

When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.

Reference: http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx

Thanks & Regards,

Arun Manglick || Tech Lead

Anonmous Types - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extesnion Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword

Anonymous Types

· Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Anonymous types are particularly useful when Querying and Transforming/Projecting/Shaping data with LINQ. Refer Scott G Post.

Note:

· There is absolutely no difference from a CLR perspective between an anonymous type and an explicitly defined/named type. Anonymous types are purely "syntactic sugar" that avoid you having to type code - the runtime semantics are the same as using explicitly defined types.

· The CLR itself actually doesn't know the difference between an Anonymous Type and a Named Type - so the runtime semantics of the two are absolutely identical.

· The actual CLR name of the anonymous type will automatically be generated by the C# compiler.

· Bart De Smet has a good blog post here that details this if you want to see the exact class name pattern and IL generated.

· This means that all of the standard .NET type reflection features work with anonymous types - which means that features like databinding to UI controls work just fine with them.

Example of using Anonymous Types in LINQ –

While instantiating anonymous types required is just to leave the type-name blank after the "new" keyword

In the code above declared is an anonymous type, as part of the select clause within the LINQ expression. Here the compiler automatically create the anonymous type with 4 properties (Id, Name, UnitPrice and TotalRevenue) - whose property names and type values are inferred from the shape of the query.

Strongly-Typed Language Support:

Though the syntax gives the dynamic language-like flexibility, it also still retain the benefits of a strongly-typed language - including support for compile-time checking and code intellisense within Visual Studio. For example, notice above how the foreach loops over the returned products sequence and we are still able to get full code intellisense and compilation checking on the anonymous type with custom properties that was inferred from the LINQ query.

See great article on its internal working by Bard De Smet. You can read his excellent post on it here.

Reference: http://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead


Lambda Expressions - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extesnion Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword

Lambda Expression

What is Lambda Expression:

Earliar C# 2.0 introduced the concept of anonymous methods, which allow code blocks to be written "in-line" where delegate values are expected.

Now, Lambda Expressions provide a more concise, functional syntax for writing anonymous methods. They end up being super useful when writing LINQ query expressions - since they provide a very compact and type-safe way to write functions that can be passed as arguments for subsequent evaluation.

Lambda Expression Example:

public class Person

{

public string FirstName { get; set; }

public int Age { get; set; }

public void GetAge()

{

List<Person> people = new List<Person>

{

new Person { FirstName = "Scott1", Age = 32 },

new Person { FirstName = "Scott2", Age = 33 },

new Person { FirstName = "Scott3", Age = 34 }

};

IEnumerable<Person> results = people.Where(p => p.FirstName == "Scott1");

double average = people.Average(p => p.Age);

}

}

The p => expressions used above are Lambda expressions.

In C# a lambda expression is syntactically written as a parameter list, followed by a => token, and then followed by the expression or statement block to execute when the expression is invoked:

params => expression

So when we wrote the lambda expression:

p => p.LastName == "Guthrie"

we were indicating that the Lambda we were defining took a parameter "p", and that the expression of code to run returns whether the p.LastName value equals "Guthrie". The fact that we named the parameter "p" is irrelevant - I could just have easily named it "o", "x", "foo" or any other name I wanted.

The actual code for above using C# 2.0 anonymous methods would be like below:

public void GetAge()

{

List<Person> people = new List<Person>

{

new Person { FirstName = "Scott1", Age = 32 },

new Person { FirstName = "Scott2", Age = 33 },

new Person { FirstName = "Scott3", Age = 34 }

};

IEnumerable<Person> results = people.Where(

delegate(Person p)

{

return p.FirstName == "Scott1";

}

);

double average = people.Average(

delegate(Person p)

{

return p.Age;

}

);

}

What is different than Anonymous Methods:

Unlike anonymous methods, which require parameter type declarations to be explicitly stated, Lambda expressions permit parameter types to be omitted and instead allow them to be inferred based on the usage. For example, when we wrote the lambda expression p=>p.LastName == "Guthrie", the compiler inferred that the p parameter was of type Person because the "Where" extension method was working on a generic List<Person> collection.

Lambda parameter types can be inferred at both compile-time and by the Visual Studio's intellisense.

Note: We can also explicitly declare the type of a parameter to a Lambda expression as below.

IEnumerable<Person> results = people.Where(Person p => p.FirstName == "Scott1");

Advanced: Lambda Expression Trees for Framework Developers

One of the things that make Lambda expressions particularly powerful from a framework developer's perspective is that they can be compiled as either a code delegate (in the form of an IL based method) or as an Expression Tree Object which can be used at runtime to Analyze, Transform Or Optimize the expression.

This ability to compile a Lambda expression to an expression tree object is an Extremely Powerful Mechanism that enables a host of scenarios - including the ability to build High Performance Object Mappers that support rich querying of data (whether from a relational database, an active directory, a web-service, etc) using a consistent query language that provides compile-time syntax checking and VS intellisense.

To read more on it refer the post.

Reference: http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead