Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

.net - Why use dynamic typing in c#?

At first I thought something like:

var aName=getAllSomethings();

Is very unreadable, and so I'll use dynamic typing just when there's no room for confusion such as:

AClassName aName = new AClassName();

Here,

var aName=new AClassName();

seems readable. But than I read (here) that dynamic typing also comes with a price in performance.
I tried reading all the other posts in that link to understand where I should use dynamic typing, but couldn't come up with even one good reason. Should I just wait for when I'll tell myself - "This can only be solved with dynamic typing" ? Or are there better (practical) reasons for using it?

Thanks.

Edit: My mistake (-: will close this question ASAP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

var isn't dynamic typing. It's just that the type of aName is inferred by the compiler.

Your example is still entirely statically typed, and has no performance penalty. Your code is compiled into exactly the same IL as it would be with an explicit type name.

Now in C# 4, dynamic typing does exist, but it would be written as:

dynamic aName = new AClassName();

My personal belief is that dynamic typing will be relatively rarely useful in C# 4 - basically when you're dealing with data which is already only known dynamically, e.g. reflection, or navigating XML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...