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
316 views
in Technique[技术] by (71.8m points)

c# - Is it a good/acceptable practice to declare variable as interface type?

Is it a good practice to declare variable using the interface? In my company we had a discussion on it and I'm quite against it.

e.g. I wanted to have a collection storing string keys and string value pairs. I don't want to allow duplicates either. So clearly I declared Dictionary variable in my class which would be exposed publicly (via property).

Dictionary<string, string> myDic;

However, a team member says that it's not a good practice ! He is saying that you declare a variable with IDictionary and this will allow consumers to assign any collection (implementing IDictionary) which they want. e.g. Hashtable or Dictionary

IDictionary myDic;
myDic = new Hashtable(); // Consumer's code

OR

mydic = new Dictionary<string, string>(); // Consumer's code -

May I know now, is it really a good practice to declare variable as type of interface? And that too when I clearly know what is expected from that variable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

For local variables, private fields, etc it's just splitting hairs. There is a benefit to defining public properties using an interface type. For example, I cringe when I see a class that exposes a property of type List<string>.

If you're using dependency injection or a composition framework like MEF then using interfaces instead of concrete implementations is highly recommended. It enables you to easily swap out implementations with test implementations.


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

...