C# 3.0 New Language Features (Part 1)

Introduction

Well, in this article I'll illustrate some of the C# 3.0 new language and compiler features and I'll illustrate the rest of the features in the second part. First of all, let's define all the new features:

  1. Implicitly Typed Local Variables and Arrays
  2. Object Initializers
  3. Collection Initializers
  4. Extension Methods
  5. Anonymous Types
  6. Lambda Expressions
  7. Query Keywords
  8. Auto-Implemented Properties
  9. Partial Method Definitions

In this article, I will define the first four features with code samples to make it clear.

Implicitly Typed Local Variables and Arrays

Instead of using the explicit type, now we can use the inferred type which means declaring any local variable as var and the type will be inferred by the compiler from the expression on the right side of the initialization statement.
This inferred type could be:

  • Built-in type
  • Anonymous type (will be discussed later)
  • User-defined type
  • Type defined in the .NET Framework class library

Now let's see how local variables can be declared with var:


 1 var int_variable  =   6 ;                  //  int_variable is compiled as an int
 2 var string_variable  =   " Mony " ;          //  string_variable is compiled as a string
 3 var int_array  =   new []  012 } ;     //  int_array is compiled as int[]
 4 //  Query is compiled as IEnumerable
 5 var Query  =
 6 from c  in  customers
 7 where  c.Name  ==   " Mony "
 8 select c;
 9 //  anonymous_variable is compiled as an anonymous type
10 var anonymous_variable  =   new   { Name = 
11var list = new List"Mony", Job = "Web Developer" }
;
12 //  Implicitly Typed Arrays
13 var int_array  =   new []  1101001000 } //  int[]
14 var string_array  =   new []  "hello"null"world" } //  string[]

Restrictions when using implicitly-typed variables are as follows :

  • var can only be used when you are to declare and initialize the local variable in the same statement.
  • The variable cannot be initialized to null.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, var i = i++; produces a compile-time error.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then you will get a compile-time error if you try to initialize a local variable with the var keyword.

Object Initializers

Sometimes you spend a lot of time writing a lot of redundant code to declare constructors that do the same job. Object initializers can be used to initialize types without writing explicit constructors.

Code Example 1
 
  
 1 private   class  Person
 2 {
 3// Auto-implemented properties
 4public int Age getset; }
 5public string Name getset; }
 6}

 7 static   void  Test()
 8 {
 9// Object initializer
10Person per = new Person { Age = 22, Name = "Mony" };
11}
Code Example 2
 
  
 1 class  Point
 2 {
 3    int x, y;
 4public int X
 5{
 6    get return x; }
 7    set { x = value; }
 8}

 9public int Y
10{
11    get return y; }
12    set { y = value; }
13}

14}

When you instantiate this class, you normally write the following code:

Point p = new
 1 class  Point
 2 {
 3int x, y;
 4public int X
 5{
 6get return x; }
 7set { x = value; }
 8}

 9public int Y
10{
11get return y; }
12set { y = value; }
13}

14}
Point(); p.X = 10;
p.Y = 20;

Instead, you can create and initialize a Point object like this:

Point p = new Point { X = 10, Y = 20 }; // object initializer

Or even like this:

var p = new Point { X = 10, Y = 20 }; // object initializer

With complex fields, such as a square or a rectangle whose corners are located at the points p1 and p2, you can create the Rectangle class as follows:

public class Rectangle
{
Point p1;
Point p2;
public Point ULcorner { get { return p1; } set { p1 = value; } }
public Point LRcorner { get { return p2; } set { p2 = value; } }
}

You can create and initialize the Rectangle object like this:

var rectangle = new Rectangle { ULcorner = new Point { X = 0, Y = 0 },
LRcorner = new Point { X = 10, Y = 20 } };

Collection Initializers

Enables initialization of collections with an initialization list rather than specific calls to Add or another method. This initialization has the same effect as using the Add method with each collection element.

public class Person
{
string _Name;
List _Intersets = new List();
public string Name { get { return _Name; } set { _Name =value; } }
public List Interests { get { return _Intersets; } }
}
class Test
{
static void Main(string[] args)
{
List
PersonList = new List
();
Person p1 = new Person();
p1.Name = "Mony Hamza";
p1.Interests.Add("Reading");
p1.Interests.Add("Running");
PersonList.Add(p1);
Person p2 = new Person();
p2.Name = "John Luke";
p2.Interests.Add("Swimming");
PersonList.Add(p2);
}
}

In C# 3.0, you can write less code to express the same concept:

static void Main(string[] args)
{
var PersonList = new List
{
new Person{ Name = "Mony Hamza", Interests = { "Reading", "Running" } },
new Person { Name = "John Luke", Interests = { "Swimming"} };
}

Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

To create an extension method, declare it as a static method in a static class. The first parameter of an extension method must be the keyword this.

The following is an example of an extension method to convert the temperature from Fahrenheit to Celsius.

namespace MyNameSpace
{
public static class MyClass
{
public static double ConvertToCelsius(this double fahrenheit)
{
return ((fahrenheit – 32) / 1.8); }
}
}
}

Now it is possible to invoke the extension method, ConvertToCelsius, as if it is an instance method:

double fahrenheit = 98.7;
double Celsius = fahrenheit.ConvertToCelsius();

So it adds a method called ConvertToCelisius to an existing type which is double here.

Hope this simple article makes the C# 3.0 new language features quite clear. In the next article, I'll discuss the other five features.

转载于:https://www.cnblogs.com/kevin-wang/archive/2008/05/02/1179328.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值