Sie sind auf Seite 1von 9

C# 3.

0 new features
In this part, we will talk about some of the new features of the C# version 3.0. Microsoft introduced this version of the C# in
August 2007. Mono C# compiler fully supported the new version by July 2008. he C# 3.0 version brought the following new
features to the language:
1.
2.
3.

Implicitly typed variables


Implicitly typed arrays
Object & collection
initializers

4.
5.
6.
7.

Automatic properties
Anonymous types
Extension methods
Query expressions

8.
9.

Lambda expressions
Expression trees

10.
11. Query expressions, lambda expressions and expression trees are beyond the scope of this tutorial. They are closely
connected to the LINQ. LINQ (Language Integrated Query) is a Microsoft .NET Framework component that adds
native data querying capabilities to .NET languages.

12.
13. Implicitly typed local variables & arrays
14. Both implicitly typed local variables & arrays are connected with the var keyword. It is an implicit data type. In some
cases, we do not have to specify the type for a variable. When the usage of the varkeyword is allowed, the compiler
will find and use the type for us. The process is called type inference.
15. In some cases, the var keyword is not allowed. It can be used only on a local variable. It cannot be applied on a field
in a class scope. It must be declared and initialized in one statement. The variable cannot be initialized to null.
16. using System;
17. public class CSharpApp
18. {
19.

static void Main()

20.

21.

int x = 34;

22.

var y = 32.3f;

23.
24.

var name = "Jane";

25.
26.

Console.WriteLine(x);

27.

Console.WriteLine(y.GetType());

28.

Console.WriteLine(name.GetType());

29.

30. }
31. We have a small example, where we use the var type.
32. int x = 34;
33. var y = 32.3f;
34. The first variable is explicitly typed, the second variable is implicitly typed. The compiler will look at the right side of
the assignment and infer the type of the variable.
35. Console.WriteLine(y.GetType());
36. Console.WriteLine(name.GetType());

37. These two lines will check the type of the two variables.
38.
39.
40.
41.

$ ./itlv.exe
34
System.Single
System.String

42. As we can see, the two variables use the familiar, built-in data types.
43. Implicitly typed arrays are arrays, in which the type of the array is inferred from the elements of the array in the array
initializer by the compiler. The rules are the same as for implicitly typed local variables. Implicitly typed arrays are
mostly used in query expressions together with anonymous types and object and collection initializers.
44. using System;
45. public class CSharpApp
46. {
47.

static void Main()

48.

49.

var items = new[] { "C#", "F#", "Python", "C" };

50.

foreach (var item in items)

51.

52.

Console.WriteLine(item);

53.

54.

55. }
56. An example demonstrating the implicitly typed arrays.
57. var items = new[] { "C#", "F#", "Python", "C" };
58. We again use the var keyword. The square brackets on the left side are omitted.
59. foreach (var item in items)
60. {
61.
Console.WriteLine(item);
62. }
63. The foreach loop is used to traverse the array. Note the use of the local implicitly typed item variable.
64.
65.
66.
67.
68.

$ ./ita.exe
C#
F#
Python
C

69. This is the output of the example.

70.
71. Object initializers
72. Object initializers give a new syntax for creating and initiating objects. Inside a pair of curly brackets {} we initiate
members of a class through a series of assignments. They are separated by comma character.

73. using System;

74.
75. public class Person
76. {
77.
private string _name;
78.
private int _age;

79.
80.
81.
82.
83.
84.

public string Name


{
get { return _name; }
set { _name = value;}
}

85.
86.
87.
88.
89.
90.

public int Age


{
get { return _age; }
set { _age = value;}
}

91.
92.
public override string ToString()
93.
{
94.
return String.Format("{0} is {1} years old", _name, _age);
95.
}
96. }

97.
98. public class ObjectInitializers
99. {
100. static void Main()
101. {
102.
Person p1 = new Person();
103.
p1.Name = "Jane";
104.
p1.Age = 17;

105.
106.

Person p2 = new Person { Name="Becky", Age=18 };

107.
108.
Console.WriteLine(p1);
109.
Console.WriteLine(p2);
110. }
111. }

112. In the above example, we have a Person class with two properties. We create two instances of this class. We use the
old way and we also use the object initializer expression.
113. public string Name
114. {
115. get { return _name; }
116. set { _name = value;}
117. }
118. This is a Name property with set a get accessors.
119. Person p1 = new Person();
120. p1.Name = "Jane";
121. p1.Age = 17;

122. This is the old way of creating an object and initiating it with values using the field notation.
123. Person p2 = new Person { Name="Becky", Age=18 };
124. This is the object initializer. Inside curly brackets, the two members are initiated.

125.
126. Collection initializers
127. Collection initializers are a way of initiating collections where the elements of a collection are specified inside curly
brackets.
128. List <string> planets = new List<string>();

129.
130. planets.Add("Mercury");
131. planets.Add("Venus");
132. planets.Add("Earth");
133. planets.Add("Mars");
134. planets.Add("Jupiter");
135. planets.Add("Saturn");
136. planets.Add("Uranus");
137. planets.Add("Neptune");
138. This is the classic way of initiating a collection. In the following example, we will use a collection initializer for the
same generic list.

139. using System;


140. using System.Collections.Generic;

141.
142. public class CollectionInitializers
143. {
144. static void Main()
145. {
146.
List <string> planets = new List <string>
147.
{"Mercury", "Venus", "Earth", "Mars", "Jupiter",
148.
"Saturn", "Uranus", "Neptune"};

149.
150.
151.
foreach (string planet in planets)
152.
{
153.
Console.WriteLine(planet);
154.
}
155. }
156. }

157. We create a generic list of planets.


158. List <string> planets = new List <string>
159. {"Mercury", "Venus", "Earth", "Mars", "Jupiter",
160.
"Saturn", "Uranus", "Neptune"};
161. This is the collection initializer expression. The planet names are specified between the curly brackets. We save a
some typing. We do not need to call the Add() method for each item of the collection.
162. $ ./collectioninitializers.exe
163. Mercury
164. Venus
165. Earth
166. Mars

167. Jupiter
168. Saturn
169. Uranus
170. Neptune
171. Here we can see the output of the collectioninitializers.exe program.

172.
173. Automatic properties
174. In a software project, there are lots of simple properties that only set or get some simple values. To simplify
programming and to make the code shorter, automatic properties were created. Note that we cannot use automatic
properties in all cases. Only for the simple ones.

175. using System;

176.
177. public class Person
178. {
179. public string Name { get; set; }
180. public int Age { get; set; }
181. }

182.
183. public class AutomaticProperties
184. {
185. static void Main()
186. {
187.
Person p = new Person();
188.
p.Name = "Jane";
189.
p.Age = 17;
190.
191.
Console.WriteLine("{0} is {1} years old",
192.
p.Name, p.Age);
193. }
194. }

195. This code is much shorter. We have a person class in which we have two properties.
196. public string Name { get; set; }
197. public int Age { get; set; }
198. Here we have two automatic properties. There is no implementation of the accessors. And there are no member
fields. The compiler will do the rest for us.
199. Person p = new Person();
200. p.Name = "Jane";
201. p.Age = 17;

202.
203. Console.WriteLine("{0} is {1} years old",
204. p.Name, p.Age);
205. We normally use the properties as usual.
206. $ ./automatic.exe
207. Jane is 17 years old
208. This is the output of the example.

209.
210. Anonymous types
211. The Person class that we have used in the previous example is said to be a type. More precisely, it is a user defined
type. The type has a name and we can explicitly create an instance of it by referring to its name. On the other hand,
anonymous types are types that do not have a name. They are class types that consist of one or more public readonly properties. No other kinds of class members are allowed.
212. Anonymous types are allow data types to encapsulate a set of properties into a single object without having to first
explicitly define a type. Anonymous types must be stored in variables declared with the var keyword, telling the C#
compiler to use type inference for the variable.
213. Anonymous types are created with the new keyword and object initializer. The compiler will infer the types of the
properties itself. It will give the type a name, but it is only used by the compiler; it is not available to the programmer.
214. An anonymous type is another syntactic sugar to reduce typing. Anonymous types are often used in LINQ
expressions.

215. using System;

216.
217. public class AnonymousType
218. {
219. static void Main()
220. {
221.
var p = new { Name="Jane", Age=17 };

222.
223.
Console.WriteLine("{0} is {1} years old", p.Name, p.Age);
224. }
225. }

226. This is an anonymous type example.


227. var p = new { Name="Jane", Age=17 };
228. An anonymous object initializer declares an anonymous type and returns an instance of that type. We use
the var keyword because we do not know the type.
229. Console.WriteLine("{0} is {1} years old", p.Name, p.Age);
230. We access the properties created using the field access notation.
231. $ ./anonymoustype.exe
232. Jane is 17 years old
233. This is the output of the example.

234.
235. Extension methods
236. Developers often face situations in which they would like to extend an existing type, but it is not possible. For
example, the class is sealed. The extension method is a workaround for such cases. Extension methods are a
special kind of a static method, but they are called as if they were instance methods on the extended type. To create
an extension method, we need a static class and a static method. When we call our extension method on a class, the
compiler does some behind the scenes processing; it appears as if we have called the extension method on the
object of a type.

237. It is also possible, and it was a common workaround in the past, to create special utility classes for such methods.
These were mostly created as static methods of static classes. Both approaches have their advantages. It is also
advised to use extension methods sparingly.

238. using System;

239.
240. public static class Util
241. {
242. public static string Reverse(this string input)
243. {
244.
char[] chars = input.ToCharArray();

245.
246.
Array.Reverse(chars);
247.
return new String(chars);
248. }
249. }

250.
251. public class ExtentionMethod
252. {
253. static void Main()
254. {
255.
string str1 = "Jane";
256.
string str2 = str1.Reverse();

257.
258.
Console.WriteLine(str2);
259. }
260. }

261. In our case, we would like to add a new method to a string class. The string class is a built-in class and it is sealed.
No inheritance is possible. This is why we need an extension method.
262. public static class Util
263. {
264. public static string Reverse(this string input)
265. {
266.
char[] chars = input.ToCharArray();

267.
268.
Array.Reverse(chars);
269.
return new String(chars);
270. }
271. }
272. We have a Reverse() extension method. This method reverses characters of a string variable. The method and its
class must be static. The static Reverse() method becomes an extension method, when we put the this modifier as
the first parameter of the method.
273. string str1 = "Jane";
274. string str2 = str1.Reverse();
275. We define and initialize a string variable. We call the Reverse() method on this variable. Even though the method is
static, we use the instance method call syntax.
276. $ ./extentionmethods.exe
277. enaJ
278. This is the output of the extentionmethods.exe program.
279. In this part of the C# tutorial we have talked about new features of the C# 3.0.

280.

Das könnte Ihnen auch gefallen