Why use dynamic typing in c#?

后端 未结 6 2253
旧时难觅i
旧时难觅i 2020-12-17 23:53

At first I thought something like:

var aName=getAllSomethings();

Is very unreadable, and so I\'ll use dynamic typing just when there\'s

6条回答
  •  执念已碎
    2020-12-18 00:24

    As everyone else has mentioned, the 'var' keyword does not give us dynamic typing. The type is inferred at compile time.

    I use var when I think it makes sense; namely, when the type is obvious and it cuts down on the verbosity of a declaration:

    var someDict = new Dictionary();
    

    Instead of...

    Dictionary() someDict = new Dictionary();
    

    However, in your example here:

    var aName=getAllSomethings();
    

    I wouldn't use 'var' because, as you have noticed already, you then have to check the return type of 'getAllSomethings()' (bad naming style for C# BTW) in order to know what 'aName' is, which just makes the code less readable.

提交回复
热议问题