Do I have to "double declare" every new instance in c#?
Obj sb = new Obj();
VB is cheaper
Dim sb as new Obj()
and Python cheapest
sb=Obj()
Do I have to "double declare" every new instance in c#?
Obj sb = new Obj();
VB is cheaper
Dim sb as new Obj()
and Python cheapest
sb=Obj()
Well, as of C# 3 you can use var
for local variables:
var x = new Dictionary<string, string>();
Note that this is very different from the Python declaration: the variable x
is still of type Dictionary<string, string>
; it's just that the compiler has inferred the type from the right-hand side of the assignment. So you'll still get IntelliSense support and all the other benefits of static typing. (If you want dynamic typing, you can use dynamic
as of C# 4, but that's a very different feature.)
This feature was partly added to support anonymous types, although it's very useful in other cases too; most notably when you are calling a constructor.
A few things to bear in mind:
The compiler has to be able to infer a concrete type from the assignment; you can't write
var x = null;
for example.
In C# 3.0 and later you can now declare them using var.
var obj = new Obj();
The following examples show some type inferences that happen without double explicit type specification (sometimes without any) as following:
int[] array = { 1, 2, 3, 5, 6, 7, 8 };
var q = from x in array
let y = x.ToString()
select y;
foreach (var item in q)
{
Console.WriteLine(item.GetType());
}
1) the right hand side of array decalration shows the array initializer alone with no type specification. Array type specification used to be required in the past.
2) var q .... where q is inferred from the right hand side.
3) from x .... the type of this range variable is inferred from the array's element type
4) let y ... the type of range variable y is again inferred from right hand side
5) foreach (var item in q) ... again the type of item inferred and not explicitly declared
There are innumerable other instances of type inference in modern versions of C# detailed in specs (e.g lamba expressions). So no , you dont have to specify it twice any more. Infact currently its quite rare to see a requirement of such explicit and potentially redundant specification (e.g. intance variable declaration)