Why implicit typing is preferred over explicit typing? [closed]
Asked Answered
W

0

7

In the C# Coding Conventions, why does Microsoft suggest using implicit typing when the type of the variable is obvious from the right side of the assignment?

I understand it's not necessary to declare it since it is obvious but why the suggestion? Doesn't explicit typing make the code easier to follow?

var str1 = "This is clearly a string.";

vs

string str2 = "This is clearly a string.";

Is there a compile time benefits for this?

Whistle answered 24/9, 2014 at 19:50 Comment(13)
No, there is no compile time benefits. And yes, explicit typing makes the code easier to follow. However, sometimes when type is complicated (like generic dictionary, or linq query results) it makes code more compact without making it less clear. At the end of the day it's still just a preference.Bettencourt
When the type of a variable is clear from the context, use var in the declaration. From the same link. Personally it is a matter of choice, I would use string in your case, I use var for things like var dictionary = new Dictionar<int,SomeclassObject>();Tritheism
@Habib, also with linq statement, as those data types can be a pain to type up-front.Lonni
Because typing redundant statements is wasting your time. And if you don't type redundant statements you can save time.Kin
personally I think this is a matter of style and preference .. for readability I would prefer the second choice but since you see " " quoted text it's obvious by sight that this is also of string type..Scup
I don't know why the down votes. This is a valid question.Sd
Malk I agree but we can't control thatScup
@Sd No, it's not a valid SO question.Kin
@user14200 - you should check #651419Bettencourt
"the guidelines in this topic are used by Microsoft to develop samples and documentation" — bull... blatant lie.Bailable
@MarcinJuraszek, surprisingly that question is marked as a duplicate, but there is no linked duplicate question :)Tritheism
@Tritheism thank you. I've also found this: [programmers.stackexchange.com/questions/125262/…. I only considered string, int etc.. but now it makes sense why they suggest it.Whistle
Sometimes I find SO just crazy. I won't understand and I don't admit discussion about how my answer could get 4 downvotes. The whole downvotes and the comment were both an opinion like my own answer. Type inference isn't a silver bullet, and explicit typing is still useful. I don't cry because declaring a list with List<string> a = new List<string>(). I cry if I need to declare something like this List<Dictionary<string, List<Person>> where explicit typing makes code harder to read.Fulgurate

© 2022 - 2024 — McMap. All rights reserved.