Книга: C# 2008 Programmer

Implicit Typing

Implicit Typing

In the previous versions of C#, all variables must be explicitly typed-declared. For example, if you want to declare a string variable, you have to do the following:

string str = "Hello World";

In C# 3.0, this is not mandatory — you can use the new var keyword to implicitly declare a variable. Here's an example:

var str = "Hello world!";

Here, str is implicitly declared as a string variable. The type of the variable declared is based on the value that it is initialized with. This method of variable declaration is known as implicit typing. Implicitly typed variables must be initialized when they are declared. The following statement will not compile:

var str; //---missing initializer---

Also notice that IntelliSense will automatically know the type of the variable declared, as evident in Figure 3-10.


Figure 3-10

You can also use implicit typing on arrays. For example, the following statement declares points to be an array containing two Point objects:

var points = new[] { new Point(1, 2), new Point(3, 4) };

When using implicit typing on arrays, all the members in the array must be of the same type. The following won't compile since its members are of different types — string and Boolean:

//---No best type found for implicitly-typed array---
var arr = new[] { "hello", true, "world" };

Implicit typing is useful in cases where you do not know the exact type of data you are manipulating and want the compiler to determine it for you. Do not confuse the Object type with implicit typing.

Variables declared as Object types need to be cast during runtime, and IntelliSense does not know their type at development time. On the other hand, implicitly typed variables are statically typed during design time, and IntelliSense is capable of providing detailed information about the type. In terms of performance, an implicitly typed variable is no different from a normal typed variable.

Implicit-typing is very useful when using LINQ queries. Chapter 14 discusses LINQ in more detail.

Оглавление книги

Оглавление статьи/книги

Генерация: 1.546. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз