Datasheet

Type Inference
x
23
C# 3.0 provides some of this, via the automatic property declaration — it assumes the task of creat-
ing a fi eld and the get/set logic to return and assign to that fi eld, respectively, but unfortunately,
C# 3.0 will choke on the
var declaration as a method parameter or as a fi eld. And 3.0 allows only
inference for local variable declarations any attempt to use these things as fi elds in an object will
require the explicit declaration and, potentially, all the disconcerting angle brackets.
Additionally, looking at the previous example, some of C#’s syntactic legacy begins to look awk-
ward — speci cally, the use of the
var as a type prefi x is somewhat redundant if the compiler is
going to infer the type directly, so why continue to use it?
// This is not legal C# 3.0
class Person
{
public Person(firstName, lastName, age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
public FirstName { get; set; }
public LastName { get; set; }
public Age { get; set; }
public FullName {
get { return FirstName + “ “ + LastName; }
}
}
Despite the compiler’s best efforts, though, it may be necessary to provide the type as a way of
avoiding ambiguity, such as when the compiler cannot infer the type or fi nds any number of poten-
tial inferences.
FirstName and LastName can be assumed to be strings, since the FullName property
adds them together against a
constant string, something (presumably) only strings can do. Age,
however, is an ambiguity: It could be just about any object type in the system, because it is never
used in a context that enables the compiler to infer its numerical status. As a result, the compiler
needs a small bit of help to get everything right.
If the type declaration prefi x syntax has been thrown away, though, then something else will have to
take its place, such as an optional type declaration suf x syntax:
// This is not legal C# 3.0
class Person
{
public Person(firstName, lastName, age : int)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
public FirstName { get; set; }
public LastName { get; set; }
public Age { get; set; }
public FullName {
get { return FirstName + “ “ + LastName; }
}
}
c01.indd 23c01.indd 23 10/1/2010 3:20:38 PM10/1/2010 3:20:38 PM