Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword?

后端 未结 3 583
南旧
南旧 2021-02-03 22:49

When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn\'t have

3条回答
  •  滥情空心
    2021-02-03 23:32

    Yes you will still need var:

    Var is a variable whose type will be inferred by the compiler.
    dynamic will have its type assigned at runtime

    So:

    Var i = "Hello World"
    

    will have its type inferred as a string type in doing so intellisence will give you all the methods that string can use like,

    i.Split("/")
    

    Where as:

    dynamic i = "Hello World"
    

    won't have its type inferred untill runtime because the complier dosn't know what type it is yet, but will still let you do:

    i.Split("/")
    

    but when it calls the method that you need it may fail because the type is wrong and the method isn't there.

提交回复
热议问题