开发者

Declaring instances in C#

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:

  • It only applies to local variables, not instance or static variables
  • You can only use it when you're declaring and assigning in the same statement
  • The compiler has to be able to infer a concrete type from the assignment; you can't write

    var x = null;
    

    for example.

  • Bear readability in mind. If it's not obvious what kind of type is being assigned, consider using an explicit declaration
  • If you later want to assign a less-specific expression, you may want to use explicit typing
  • Implicit typing helps to emphasize what the code is doing rather than how it's doing it; for bits of code where the "how" is particularly important, consider still using an explicit declaration


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜