syntax - Declaring instances in C# -


Do I have to "double declare" every new example in C #?

Obj sb = New Obj ();

VB is cheaper

  Dim SB as the new ob  

and Python cheap

  sb = Obj ()  

Good, C # 3 In the form you can use var for local variables:

  var x = new dictionary & lt; String, string & gt; ();  

Note that this dragon is very different from the declaration: variable x still word & lt; String, string & gt; ; It's just that the compiler has guessed the type from the right side of the assignment. You will still get all other benefits of intelligencing support and stable typing. (If you want dynamic typing, you can use the dynamic as C # 4, but this is a very different feature.)

This feature is partly The form has been added in support of anonymous types, although it is also very useful in other cases; Most especially when you are are calling a producer

Keep in mind some things:

  • This only applies to local variables, not examples or static variables
  • < Li> You can only use it when you are announcing and tell in the same statement
  • The compiler should be able to guess a solid type from the assignment; You can not write

      var x = null; For example  

    .

  • Keep readability in mind. If it is unclear what kind of type is being assigned, consider using a clear declaration
  • If you want to allocate a less-specific expression later, then you can type clear typing You may want to use
  • Emphasize typing what helps to emphasize how is doing the code instead of doing it on the code ; For the bits of code where "how" is particularly important, a clear declaration

Comments