New Features of C# 3.0


One of the frequently asked questions in interview is “What are the new features added in C# 3.0”.

Following are the new feature added in C# 3.0

1. Automatic Properties

Automatic properties provide you with a shorthand method for defining a new property.

public class AutomaticProperties

{

// Automatic Properties

public int Id { get; set; }

public string Description { get; set; }

// Normal Property

private decimal _Price;

public decimal Price

{

get { return _Price; }

set { _Price = value; }

}

}

2. Initializers

we can use initializer  to reduce the amount of work it takes to create the new instance of a class. Syntax is like that.

public class Product

{

public int Id { get; set; }

public string Name { get; set; }

public decimal Price { get; set; }

}

Product product2 = new Product {Id=1, Name=”Laptop Computer”, Price=40000.00  };

In C# 2.0 we have to initialize like this

Product product1 = new Product();

product1.Id = 1;

product1.Name = “Laptop Computer”;

product1.Price = 40000.00;

3. Type Inference

We can create the variable like JavaScript. C# Compiler determine the type of variable at compile time.

For example in C#, we can write like this

var message = “Hello World!”;

4.Anonymous Types

Anonymous Types are essentially compiler generated types

Anonymous types are useful when

  • you don’t want to do the work to create the class.
  • You don’t know the return data type

For example, I can write like this

Var customer=new Customer {FirstName=”Chandradev” LastName=”Prasad”}

5.Lambda Expression

It is used to wired of the event. For example,if you want to programmatically wire up the click event handler to button Control. Then we can write like this.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Init()

{

BtnSubmit.Click += (Sender, e) => lblMsg.Text = DateTime.Now.ToString();

}

protected void Page_Load(object sender, EventArgs e)

{

}

}

Advertisements

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: