Sudheer Kumar

ASP.Net, C#, BizTalk, MSBuild, WPF, WCF, WF....
posts - 28, comments - 111, trackbacks - 16

My Links

News



Archives

Post Categories

Thursday, March 27, 2008

C# 3.5 Cool Features:

C# 3.5 provides a lot of good features and here are a few of them.

Implicitly Typed Local Variables:

The compiler derives the type from the initialized value.

// Implicitly typed local variables.

var myInt = 0;

var myBool = true;

var myString = "Time, marches on...";

 

These are greatly useful while using with LINQ.

Automatic properties:

No need to write the entire property syntax.

class Car

{

// Automatic property syntax.

public string PetName { get; set; }

}

 

·        But they cannot be used to define read-only or write only properties

// Read-only property? Error!

public int MyReadOnlyProp { get; }

 

·        Abstract Automatic Property can be defines as :

abstract class Car

{

// Abstract property in an abstract base class.

public abstract string PetName { get; set; }

}

 

·        Restricted Access to Automatic Properties:

Get can be public and set can be protected.

public string PetName { get; protected set; }

 

·        Default values are assigned automatically:

In the above case, PetName is assigned null when declared.
 

Extension Methods:

                                                               i.      This technique can be quite helpful when you need to inject new functionality into types for which you do not have an existing code base.

                                                             ii.      Extension methods are static methods and can be defined on any class for any other type.

The following code extends System.Object to have a new method.

static class MyExtensions

{

// This method allows any object to display the //assembly it is defined in.

public static void DisplayDefiningAssembly(this object obj)

{

Console.WriteLine("{0} lives here:\n\t->{1}\n", obj.GetType().Name,

Assembly.GetAssembly(obj.GetType()));

}

}

 

o   this on the first parameter mentions the extended method.

o   this can only be applied to first argument

o   Extension methods can take multiple arguments

 

                                                            iii.      Calling Extension Methods:

1.      On instance

int i = 0;

i.GetAssembly();

 

2.      Using static way:

MyExtensions.DisplayDefiningAssembly(myInt);

 

More on this later....

Posted On Thursday, March 27, 2008 6:21 PM | Feedback (11) | Filed Under [ .Net 3.0/3.5 ]

Powered by: