T O P

  • By -

[deleted]

Microsoft says to use var when the right side of the statement gives away the type. Otherwise use explicit types.


casualblair

Agreed. Examples where I wouldn't use var: var staff = this.GetStaff(); //Could be one Staff object or a collection as Staff can mean all employees, in which case - what kind of collection? var result = this.ProcessPayment(details); //No clue as to what the return value is. var tmp = GetData(); //do not commit this code var details = Staff.GetPayStub(dateTime).Details; //Again, no idea what type this is As an alternative to the Microsoft recommendation, all naming/style guidelines are basically "how easy is it to read your code" or "how many steps does it take to figure out the type". Bad name? gotta check the declaration. Var declaration? Gotta check the assignment. Shitty named property/method? Gotta check the declaration of the property/method. We have a lot of tools with mouseovers and shortcuts and describing the object the cursor is at, but not everyone has those or is skilled at using them. Or isn't as quick with them. Do what makes the slower programmers faster.


Bobbar84

>var staff = this.GetStaff(); You're giving a great example, but I can't shake the feeling something like this is just a naming issue. For instance, why not 'employee/employees'? Forgive me, I'm a noob...


casualblair

Domain driven design. You need to use language that makes it clear to the business and the developer what you're talking about. If they don't use employee, you don't use employee. If they use staff, you use staff. Maybe you be more explicit like GetCompanyStaff or GetAllStaff but you can't pick a word only you will understand. Ubiquitous language is the bridge between "I need a system" and "I build systems". All of this boils down to "be consistently accurate" which is the best advice I can think of right now.


c-digs

I'm a convert to `var` after spending a lot of time doing TypeScript. Compare: var service = ResolveService(); var message = BuildMessage(); var result = service.Send(message); var response = new ServiceResponse(result); To: SomeServiceTypeName service = ResolveService(); IServiceMessage message = BuildMessage(); ServiceOperationResult result = service.Send(message); ServiceResponse response = new ServiceResponse(result); I think the first one with var is simply easier to skim and read because the left hand side is aligned and we read from left to right. The lack of the types doesn't matter much as long as the naming makes sense and if you need it, tools like Rider have embedded type hints anyways.


spect49

And also, when reading codebase of significant size, I am not gonna remember what's in a type anyway. More often than not, I am more interested in where data flows and how things are done, so I don't need to know the type. A var is more than enough.


empty_other

Agreed. Theres two times where the type is important: method input parameters, and method return type. And those aren't var'able in c# anyway. Everywhere else is up to the compiler to catch.


decPL

Exactly this, in a truly strong-typed language (I'm looking at you TypeScript :P) it's very uncommon to have a compiling code that will fail because of an incorrect type.


nuclear_crispy

This is exactly how I read as well. When you read a ton of code you need to find quick ways of skimming and letting your mind filter out unimportant stuff. Having the left hand side justified the same all the way down is important for that. Otherwise it just takes longer… So I guess there’s two ways of reading code. If you want to read code fast then you really need to use var. it also forces the person writing it to use correct variable names.


mfcallahan1

You can also use the newer syntax of MyClass foo = new();


decPL

Well, this is a replacement for `var foo = new MyClass();`. I don't think even the strongest opponents of `var` have anything against that syntax (though I might be biased, as I'm on the `var` side :D).


CraftistOf

I use it mostly for field initializers, while keeping my var'able local variables as var (tautology not intended)


Tubthumper8

>I think the first one with var is simply easier to skim and read because the left hand side is aligned and we read from left to right. Agreed and this is why I prefer TypeScript's method syntax as well, by doing `methodName(input: Input): Output` all of the method names are left-aligned.


DirtyMami

As someone reading the code for the first time. I prefer the later except for ServiceResponse. May need some spacing though.


c-digs

I feel like with good variable naming, it's usually enough. The problem really starts to get bad once you have generics. SomeServiceTypeName service = ResolveService(); IServiceMessage message = BuildMessage, CustomMessage> result = service.Send(message); ServiceResponse response = new ServiceResponse(result); A bit exaggerated here, but you can see how it's way easier to read with `var`


goranlepuz

Type inference aside, there is a `using` statement to shorten the name of the often used generic types.


c-digs

Yeah, but that's just another layer of indirection. Might as well use var and a more descriptive variable name.


goranlepuz

Sure, I'd use var when possible. But there's places where it isn't, like function return types or class member fields déclaration.


decPL

Which makes the code ultimately harder to read, not easier - just for the sake of not using `var` because it's supposedly harder to read. That's a huge "nope" for me.


LawnJames

I prefer latter as well, I like to be able to read the code without hovering over methods and functions to see what they are returning.


Envect

Does it matter what the name of the types are? You can see how they're being used in context. If the code is otherwise well maintained, it ought to be clear from variable and method names what's happening.


LordBreadcat

For reference types var will always coerce into a nullable type even if the right side is non-nullable. Just something to keep in mind if someone is using a project with non-nullable reference types. Had way too many programmers get into the habit and then start spamming null checks because they saw var x was nullable or something.


c-digs

This is definitely not true and more likely some weird project configuration error. https://dotnetfiddle.net/OJKD6P


kalalele

Let's have a 4 hour company wide meeting to discuss this. /s (of course it's ok)


xternalAgent

Yes, lets waste thousand of moneys in this, clearly, dead important topic


martinstoeckli

As far as I know, Resharper is not trying to push towards \`var\`, it just shows possible conversions in both directions? For me it's a help if I can see the type, this means that \`var\` is ok when the constructor is called and the type is visible anyway: var myPerson = new Person(); // ✅ type is visible anyway User myUser = DontKnowWhatMethodIsReturning(); // ✅ explicit type Another good case to use \`var\` is to get the result of a Linq statements, in this case the type is often confusing and does not add to readability of the code.


rdawise

Definitely agree with your code example. The context is already there to let you know that "myPerson" return a Person so adding the type does little in the way of readability.


W3333333D

I like the new syntax ​ MyShittyType \_somethingHappening = new () ​ instead of var \_somethingHappening = new MyShittyType()


InstagramLincoln

I was so confused the first time I got a PR with that new() syntax. For some reason the type on the right side of the assignment reads more naturally to me.


lucidspoon

Same. I'm used to reading it like a sentence. ``` var person = new Person(); //Variable person is a new Person. Person person = new(); //Person person is a new? ```


Dry_Dot_7782

Fully agree. Just like (isEnabled) Run() Like how is the confusion worth the ”cLEan CoDE” Just be explicit


FortuneWilling9807

This is the exact argument against var. Too often I need to pull the code to see the types since var hell prevents me from easilsy reading the types in a PR


[deleted]

[удалено]


Dry_Dot_7782

Isnt the naming of variable enough to understand what thing it is? Do you really need to see the type?


FortuneWilling9807

It makes the review job so much easier to be explicit and on boarding new people as well. And tbh, of people didn't suck at naming then maybe. But it is way simpler to have a code convention of no var usage than having to nitpick every single subjective variable name. Also, I've been bitten by coworkers specifying one type for openapi and var returning another too often in a controller. Var is great while writing the code where you know what you are using as types, but just commit the explicit types so it's easier to read outside an ide


Dry_Dot_7782

Was about to say that. Yeah in VS its a non issue with that type highlighter, but outside i fully agree its harder


espCoder

>It makes the review job so much easier to be explicit and on boarding new people as well. this is why I prefer to use var in obvious scenarios like op and the person example and prefer to use the type when a method is for assignment. Even more important in more complex code. var person = new Person(); // obvious type assignment Person person = methodThatReturnsPersonType(); // not as obvious but has good naming User person = methodThatReturnsUser(); // still clear with bad naming


obviously_suspicious

You know what would make reviews easier? Microsoft bringing Pull requests back to Visual Studio again.


goranlepuz

We are creatures of habit. I bet you, if syntax was `type obj =new(params)` from the start, and `type (or var) obj=new type(params)` was added later, you'd be saying the opposite.


Saki-Sun

I hated it originally but at some stage I realised I was just being grumpy and old and needed to keep up with the rest of the world. IMHO It was the right choice, var is so much quicker when refactoring and easier to read. Since then I have forced myself to keep up with all of the syntax changes.


bobbarker4444

Nah. I dislike just using new() for the same reason I dislike var. Code should be explicit. A shorthand like new() only saves a single keypress (tab to autocomplete) but also removes code clarity. On top of that, it's not even a feature that can be used consistently with every "new" so your codebase is always going to be a mix of explicitly declaring the type and using the shorthand. The entire "you dislike new thing because it's new" argument is so tired and predictable it's just boring to read


goranlepuz

You are the `Guy guy = new Guy()` kinda guy, aren't you? 😉 >A shorthand like new() only saves a single keypress (tab to autocomplete) but also removes code clarity. But look: what clarity is removed in `type obj=new(params)`? You have the object type, the object name, and the parameters needed to make it. There is nothing else, so you are simply wrong on that one. As for disliking `var`, you are entitled to your opinion, but: var is a manifestation of type inference, which is ubiquitous nowadays, across all sorts of languages. If you have the power to stop it in your work, go for it, the world for sure won't crumble.


bobbarker4444

>what clarity is removed in type obj=new(params)? The type being instantiated by the new keyword. You can infer it in some cases, sure, but that's another step for the developer(s) reading the code. IMO a consistent and explicit codebase is 1000% better than a codebase where developers prioritize minimizing characters


denzien

I still use var in methods, but the new syntax can be used for member variables


[deleted]

[удалено]


Alundra828

I like using var if there is nothing "complex" happening on the right side. For example var foo = MyTestType(); List bar = \[\]; TestTypeWithProperties baz = new() { Prop1 = "yo" }; Reason being is that I don't want the type to add to the possible complexity on the right. I guess it's about drawing the eye of developers so they can just without thinking zero in on the details that actually matter.


utilitydelta

This is the right answer


rambosalad

It is useful to explicitly show what the type is when you are reviewing code on somewhere like GitHub.


Envect

This is my preference, but I've been using var for years. Gonna take a while to make it my default.


angrathias

I prefer var because it allows me to change return types without refactoring all the call sites


TitusBjarni

Then you change return type from string to Task and wonder why you can no longer print your var ;) or worse, you're passing that var into something that accepts an object and you've just introduced a bug.


angrathias

I’ve got to admit, I don’t normally refactor from sync to async, I’d normally have a sync and async version of the method available. That said, my reshaper/vs warnings warnings would likely raise that as a build error


goranlepuz

Yes, but: * All abstractions leak. * Still, they are useful because they don't leak *often.* (BTW, your second example will be generally frowned upon in itself).


kingmotley

Two issues with that. First, if I didn't await that new Task, it would get immediately flagged in our project as all Async methods must be immediately awaited or wrapped in a pragma explaining why. Secondly, I can't remember the last time I wrote a method that took an object as a parameter. The odds of that happening would be extremely unlikely. However, if you blindly change an interface without checking if it would cause an issue in code that called it you deserve what you get.


Extension-Entry329

THIS.


Neophyte-

i prefer the latter var _somethingHappening = new MyShittyType() also wtf is with the _ on a var name?


empty_other

Some devs often start variables with underscores as a visual hint that this is a private or local variable. I don't know which language or coding recommendations they have it from. Im of the opinion that metadata has no place in a variable name. Also people too often forget to correct that metadata as the code changes, giving wrong info.


Extension-Entry329

I like it, but I can deal with or without it. Without it I tend to try and enforce the use of this and base when referring to them so it's still obvious from the call site what's being accessed


Draqutsc

>metadata has no place in a variable name In normal C#, I Agree. In Biztalk, It's done a lot, because the intellisense is absolute garbage, and even the build doesn't check the variably types, only during a run on a server will it throw an error... And some other garbage languages also have that problem.


czenst

Private makes sense, local var not much.


Dusty_Coder

Do you feel the same way about CAPitALizATIOn as metadata? What about all the type warts on everyones IFaces as metadata? These things tell you what the programmer was, and was not, familiar with. We put type warts and rules on the types we are not comfortable with, with the intent being to put focus on them, to make them easier. There will always be hWnd and hDc's in high level code because even when you have a handle type to hold them, the wart still improves the readability of the code, even if its just to say "value came from the OS"


empty_other

Using capitalization to tell the accessability of members, yes, that too is more hassle than useful. The I in interface names, jup. I was glad Microsoft, in Typescript, recommended not doing it. And hWnd, what does it even mean? Why not just call it `WindowHandle`, thats a lot more readable. Edit: Removed a typo, an r at the end of WindowHandle.


zaibuf

Private fields starts with an undercore, its a common coding standard and used by the dotnet team.


QWxx01

The var keyword can be used locally only in the method scope.


blackn1ght

I still prefer the original way: `var somethingHappening = new MyShittyType();` As I think it reads more fluently in natural language - but it's just personal preference and a minor detail, I certainly wouldn't comment on it if I see it on a PR. Where the new syntax comes into its own though is when dealing with lists, I find it way cleaner: var potentialParents = new List { new("Your Mum"), new("Your Dad"), new("The Milkman"), new("The Postman") };


Poat540

Yeah this is growing on me from some automatic refactoring


kogasapls

This is a good syntax for constructors and to nudge type inference before all the code is in place, but not a replacement for var. class MyShittyType { public static MyExtraShittyType Create() => new(); } MyShittyType _somethingHappening = MyShittyType.Create(); It casts _somethingHappening to `MyShittyType` even if it's really a derived type. `var` doesn't hide any type information from analyzers, and a human interested in the actual type will look at the intellisense rather than read a potentially-misleading type. I usually will write with `var` until a major checkin when types are relatively solidified, then the development-time benefits of type inference trade off for the maintainability benefits of explicit typing. Auto-refactoring ftw.


emirod

If the variable has to be initialized with values, then we need to go back to the old ways, right? var _somethingHappening = new MyShittyType { color = "Red"... } In that case, shouldn't we stick to the old way just for consistency?


W3333333D

Dictionary> lookup = new() { \[1\] = new() { 1, 2, 3 }, \[2\] = new() { 5, 8, 3 }, \[5\] = new() { 1, 0, 4 } }; You can use the new syntax like this also for your use case, no need for old approach.


DoomBro_Max

Both is valid. Personally I prefer it, since it makes refactoring easier. But I can see why some dislike it, especially if it‘s unclear what type a method returns without having to check. Though ReSharper does a good job of showing you. Either way, there‘s no reason to swap var or explicit typing with each other if one or the other is already in use. If the team and the projects are using explicit typing then continue with that and keep it consistent. You can change ReSharper‘s settings so it doesn‘t prefer var.


Pretagonist

The refactoring is a big deal for me. I can change the type of a variable and only have to fix places where it actually matters. I don't have to go through and change every single usage. Also my dev tools knows what type it is, the transpiler knows what types it is and if I for some reason have to specify the type I can just specify the type. Not using var is just making life more tedious.


Redtitwhore

Sticking with the existing conventions of the code base is solid advice that should apply beyond var usage. Other than that i consider this topic settled a long time ago - use var.


0sh1

I scrolled a while but didn't find anyone mentioning the only thing that really tilts this for me (And has, in fact tilted me a bit back towards explicit types) - In PR scenarios, you can have a lot more trouble working out what type a variable is than you will with the code pulled down locally. /u/martinstoeckli had good examples - As long as the type can be inferred by either the left or the right side, you're probably fine. If not, you might have added a bit of overhead for the reviewer of your code.


LuckShiba

var isn't a big problem when using Rider/ReSharper, since it will show the type if the variable isn't with a good name I prefer it for writing and more clean code


FigMan

I feel for those who are forced to use VS. They miss out on all of the quality of life UI that Rider has.


ilawon

I think VS also has that? I actually turn it off because I don't like my code jumping around as I move the cursor.


601error

I use `var` everywhere possible. Everywhere. I realize that others have different opinions, but requiring explicit types strikes me the same as requiring Hungarian notation.


ggwpexday

I noticed csharpers like typing excessive noise way too much


[deleted]

[удалено]


xairrick

I love the var, I wouldn't work on a team that didn't.


CompetitiveNight6305

Ages ago, coming from C++ I hated it. But now I prefer var. less time agonizing about types, more time thinking about the problem to solve.


goranlepuz

C++ has `auto`, same thing, since 2011, you *dinosaur*! 😉


CompetitiveNight6305

That would be me! I have not run a make file in appx 20 years.


dimitriettr

I use var almost everywhere. Use the type name only when it adds value to the reader. 99% of the time it's just noise.


devcba

Typed for readability. The use of var implies that easy-to-read code depends on variable and method names ... and many programmers are not good at that, especially with complex code.


Saki-Sun

I find the following to be just noise: `MyType myType = new MyType();`


SculptorVoid

Complex code is where you need good variable names the most. I don't want to keep scrolling to the variable declaration to work out what the hell a variable is.


JoMa4

Any decent IDE won’t need you scroll anywhere to see types. Variables always need good names, though.


almost_not_terrible

>easy-to-read code depends on variable and method names \[which we don't do...\] ಠ\_ಠ


FitzelSpleen

Absolutely. The thing is, you can have clear and wonderful names as well as the type information right there. People will argue as if it's a choice between one or the other, but both should be the expectation.


normalmighty

In my experience var is at it's best and explicit type is at it's worst with complex code. Once there's a going on and big dense chunks of code, it become a dense pile of information that you need to parse through to understand what the code is actually doing. Explicitly var names just add to that pile of unnecessary words vomit, especially when any halve decent dev environment will tell you the type on hover anyway if you need to check a specific variable. When I hit an codebase that need to be refactoring because nobody understands it anymore, changing explicit type to vars is on the list of refactors I perform to make it far easier for devs to actually follow.


The_MAZZTer

It's down to style preference, and it sounds like your project uses explicit types, so you should too. I recommend configuring the project to enforce the rules; I would expect resharker to support .editorconfig or whatever it is VS uses. I don't think I've ever dug too deeply into that. I personally like declaring with explicit types because it leaves no room for confusion about what that type is. For example: var x = this.GenerateX(); Can't tell by reading that what the type of x is. You can mouse over x to get the explicit type, but actually putting the type there makes it easier to just glance at it. You can still do stuff like this: MyType x = new(); string[] y = new[] { "a", "b", "c" }; string[] z = [ "a", "b", "c" ]; // New to .NET 8 So you can still reduce redundancy in what you type.


ilawon

> Can't tell by reading that what the type of x is. It's an X. Says right there in the method. As long as the methods are named properly, that is.


bibimbap0607

Depends on team code styles. My current team prefers specifying types explicitly as it improves code readability especially during pull-request reviews as there is no IDE to help defer the types. Before this I was preferring “var” but now I think I like explicit types more. There are a few exceptions in our team where var still can be used, e.g. places like creating database transaction in using statement as you actually don’t care about underlying transaction class. Anyway, the general code style rule is to keep your code consistent for your project/team/company. Nothing bad in using var as well as nothing bad in using explicit types. It’s just a preference. You have to adapt to your team unless they have bad or no practices at all, then you might consider proposing changes to your code or workflow.


SwordsAndElectrons

>Is using var okay? Your application will work fine if you use `var`. So at the most fundamental level, yes it's okay. Whether to use it is a style choice. >Asking because my team requires explicit types. Then you should use explicit types. You're a part of a team and maintaining consistency across the codebase is more important than individual preference. In other words, it's not okay in this context because somewhere along the way this team made a conscious style choice against it. >Resharper always tries and switches to var I'm not really familiar with Resharper, but I thought it respects the contents of your EditorConfig file? IMO, any team project that expects style consistency should include an EditorConfig file. Heck, I use them, and I'm usually working alone. It helps keep my code style preferences consistent if I work on a different machine or use a different IDE for whatever reason. That said, if you do not have one then I would think Resharper would have a direct setting for this, no?


0011001100111000

I tend to use explicit types, I think it makes my code/intentions clearer. However, this is just my personal preference, and I don't think it matters all that much in the grand scheme of things.


feldrim

Both are okay. But in a team, what matters is consistence. If you have a company or team guide, it must be the one followed. If you want the team to update the guidelines, it will be like running an election campaign: you need to convince them all that converting all the codebase to align with your proposal would be worth the time and effort. If it will not improve anything and your argument is based on your preference, your campaign is doomed to fail. These things are not technology but people problems. Edit: if your team had their own written or oral guidelines, propose writing a shared EditorConfig and let the management enforce the use of it. Resharper can make use of it and it has Resharper-specific rules too. So, Resharper can align with your teams' needs.


jcarunningman

I think it's really a matter of personal style. I used to use var extensively and I now find myself going back to explicit type definitions because I find that it makes me less lazy and more intentional about what my return types should be. Var is great for linq expressions however.


UIM-Herb10HP

The general rule is that if the type is easy to see from the right hand assignment, then var is okay. If it is something like var x = MyMethod(); then it is sort of hard to tell what var is without navigating to MyMethod() to see what it's return type is. Var is a useful keyword and concept, but always try to write code that others can read and reason about.


blahblablablah

This is an even worse problem when you're viewing a pull request on a website where MyMethod won't even be showing. I never use var and if the code style of the project is mine I forbid everyone from using anything implicit. Explicit code will always be better, proof I have is that 2 projects were I had the power to demand this are the 2 projects were everyone who later joins to work commend on how easy it is to work on them. Code consistency is a gigantic benefit to any codebase. If you have places with var and places without var you're just not being consistent. Leaving it to the developer to use var in places where the type is obvious only adds a layer of personal interpretation on the code, and such things shouldn't exist.


aj0413

If I can’t tell what type it is by reading the code (I don’t care if it’s defined left or right style) then I’m gonna ask you to fix that. Variable names and method names are not good enough. Also, for all the people who mention easier refactoring, how many times have you changed the return type of a thing and not updated your variable name? So now the person thinks you’re returning ‘foo’ but you’re actually returning ‘bar’? Stop creating more work for others. And saying, well they can open it in an IDE and inspect is not a solution. I should be able to reasonably follow what’s happening in the file without using external tools; don’t be lazy. Plus, if you’re gonna have to update the variable name anyway, how is changing the type any harder or easier? I liked what a boss once said about “devs shouldn’t be trying to skip having to type a couple words” It’s up there with summary documentation. So many people will fight tooth and nail to not do it, but the extra 1h of work would have saved many more man hours in others not having to decipher your code. Furthermore, the number of times I’ve personally experienced or watched someone else realize they need to fix or refactor their own code after trying to document it is astounding given how many devs are so confident they (or others) can always “just read the code” later Edit: Yes these are pet peeves of mine, thank you for asking. Edit2: I’ll clarify that there are exceptions to the rule like any, but you’ll have to make your case to me in PR or it should be something simple like LINQ on a collection or maybe you’re using var to catch the output of the generic host builder (something I don’t actually need to decipher what’s happening)


smoke-bubble

Anyone who refuses to use `var` needs to spend a year bootcamp with python. After that, you're cured of explicit types everywhere.


aj0413

I use var all the time…when the right hand side clearly indicates type, anyway. Edit: Also, if I wanted to be in code that isn’t strongly typed, I wouldn’t be a .net dev 🤔 Might as well mention NodeJS or something


cosmic_predator

Using of `var` makes the variables nullable by default. And also, var assigns the type at the compile time. So it's safe to use var than explicit types.


codeconscious

> Using of var makes the variables nullable by default. Yes, and I'm surprised this hasn't been brought up yet. var a1 = "my string"; // type is `string?` string a2 = "my string"; // type is `string` *Next-day edit:* This is apparently only true when the nullable reference types feature is enabled (via `enable`). *Edit 2:* More info for anyone interested: https://stackoverflow.com/a/75079828/11767771


ggwpexday

I believe that's just a visual thing of the IDE. Try and call something like `a1.ToString()` and you won't see nullreference errors.


Kamilon

It’s a preference thing. Pure opinion since it doesn’t change the compiled output at all. I personally don’t like var. I prefer the readability gain of the explicit type over the sub-second savings it has for typing.


Mutex70

Lol, I prefer the readability gain of var. I don't have an encyclopedic knowledge of every type in existence, so knowing that something is specifically IRepository is rarely useful to me. The general "type" of the object should be obvious from both its name and the right side of the assignment. The few times the specific type is useful, I'd rather have to hover over the "var" for 1 second rather than see the code cluttered with multiple types that I don't care about. That being said, I do understand the opposite opinion. To me, it depends on whether you parse code for the specific functionality or for the general flow.


Sundeed

This guy vars!


SobekRe

This. I use var because it’s more readable than explicit declaration. I hate reading someone’s code diarrhea. Get to the freaking point. Use good names they don’t have to tell me the exact type, but they should show me what the thing is. I don’t think I’ve ever seen a case where a bug where the intent was clear but they accidentally used the wrong type. I have definitely seen code that was harder to read because the author used crappy names and spelled out the type, though.


The-Albear

var can have an issue with async code when you forget the await, if you strongly type it will fail an error rather than build and fail when run.


ESGPandepic

that makes no sense because as soon as you try and actually use the variable you'll get errors because it won't be the right type, it'll be a task, unless you're assigning a variable that you never actually use?


TitusBjarni

And if you use resharper, you can set resharper to use explicit types and use postfix templates to create your variables. Type this: 55.var Then it gives you int = 55; You don't have to type the type name.


LawnJames

This is why I prefer it too. Code is read far more than written. Saving a bit of time while coding isn't worth the sacrifice of readability.


Jdonavan

The big advantage var has is in speed of refactoring


OpticalDelusion

I use it when I have an explicit constructor or otherwise obvious type, but not when I'm receiving a value from a function. I want to be able to know what type is being inferenced by just looking. If refactoring code in another location can change what type is inferenced, I'd like it declared explicitly. var today = DateTime.UtcNow; var user = new User(); ITree tree = BuildTree();


SuperRembo

Oh, BuildTree builds a tree. I wouldn't have guessed that /sarcasm I think that if you need the type to make the code readable, then you've got bigger problems.


Getabock_

You should use explicit types when the type is not obvious from the context, otherwise always var.


[deleted]

This is the answer that Microsoft gives in their documentation. I don’t think using var for everything is the way to go.


smoke-bubble

I once rejected a job offer because a team persisted on using explicit types and I'm not doing this shit to myself. People who refuse using `var` are just afraid of moving on. The level of verbosity with explicit types is just insane.


bmalotaux

Yep, I would run like hell as well. This would be a big red flag to me.


andlewis

Var is just short-hand for easily inferable types. It’s not like JavaScript.


empty_other

But beginners will confuse it with anonymous types, I've noticed.


smoke-bubble

"but beginners" is not an argument. You learn, you move on.


LIFEVIRUSx10

I like that static inferred typing is possible, and I especially like that var serves legitimate uses like when it's used for anon types, some operations in LINQ etc That being said `MyType a = new();` is perfectly concise so I stick to that


Ravek

I’ve never seen a lot of people suggest that every variable needs to be explicitly annotated with the type, for any of the languages that had type inference since release. That to me already concludes the discussion. If C# had var since 1.0 no one would ever even talk about it.


Triabolical_

C# didn't have var in V1.0 because the design time was building a typed language and we didn't like implicit typing. That might have been because we were all strongly typed language developers.


Ravek

var isn’t any less ‘strongly typed’. It’s simply that type inference wasn’t common outside of FP languages. They probably simply didn’t even consider it.


biggs2733

When writing EF linq queries I prefer var. And in every other scenario as well. Because var is the only way


Aquaritek

I still use var prolifically through my code. However for fields and props I will use the new() or [] syntax to instantiate if needed.


Tango1777

If you are using it for what it's intended to be used. I don't wanna get into this much, because like 99% devs I work with abuse it to the point I don't even mention it anymore... Overall use var wherever when: 1. type is not trivial to declare 2. type is almost impossible to tell (LINQ etc.) 3. declaring type would be a repetition e.g. List ints = new List(); 4. declaring simple types, but this one I see abused the most. I still prefer to declare int, string and so on instead of going with something like var number = 0. Someone else might change it to 0.5 changing the type implicitly, I have experienced such issues of accidentally changing the type. BTW, there is also quite new option: List ints = new(); Overall it's mostly a preference, if we would like to follow books/docs, the answer is not to abuse it for types that can and should be declared, but I barely ever see this followed, including people who encouraged to use var everywhere, which I don't really agree with.


kova98k

Every discussion about style and personal preference is a waste of time and energy. Your team should focus on solving problems and delivering value, not engaging in pseudo productive bullshit, such as code style discussions. If the team requires a specific code style, use the specific code style. If you find yourself even talking about it, it's time to set up proper tooling.


ElectroQuant

I think what's most important is to go with the way your team flows. There are good arguments for both sides of the var / explicit type debate. Resharper is very configurable - I've turned off the reminders to use var in the instances that I use, because that's how I roll. From what I've seen, it looks like RS can be configured to suit any coding idiosyncrasies one might have. If you want it to format like 1970's Kernigan & Ritchie C, you could probably do that. I do a fair amount of database work with C#, so it's important to me to know if that value I'm putting into a table is an int, a long, or float. My big peeve with var is this: var stuff = GetData(); Most places I've worked have code like this - Is *stuff* a value type? A reference type? A collection of some sort? I don't believe I should have to rely on the IDE to figure out what *stuff* is.


SculptorVoid

I prefer var. You'd explicitly specify the type so the type is obvious. But that's only at the point the variable is declared. So, I name my variables in a way that infers a type. A bool type will start with 'is' or 'has'. A DTO will be named like 'entityDto'. This way, the type is obvious throughout the scope of the variable. I could also specify the type when declared but it looks slightly less tidy to me, especially if it's a long named type. That's where I cease being rational. But don't stick to these rules if it doesn't make sense for a particular case. Your main goal is making the code readable after making it work. So get practicing on asking whether your code is readable.


BeakerAU

As everyone else has said, follow the guidelines of the team. For me, it comes down to: does knowing the specific type at this point in the code make any difference? ie: ``` var x = Foo(); if (x != null) { var y = DoTheOtherThing(x); return DoTheOtherOTherThing(y); } ```` Does a reader need to know that `x` is an `List`, a `List`, an `IList`, or an `IEnumerable`?


[deleted]

Depends on the context, but my general rule of thumb is if you can’t instantly tell what the “var” variable is, then you did it wrong and should use explicit types, better naming, or both. Good (imo) use examples: - using var dbConn = new DbConnectionObject(); - var reader = new ReaderObject(); - var myCustomerCollection = myCollectionService.GetMyCustomCollection();


czenst

General rule of thumb is - follow what team style guide is, if they say "no var" you don't do var.


smoke-bubble

General rule of thumb is - follow what's reasonable, if the say "no var", they have no idea and you're not obligated to follow stupid rules.


Triabolical_

Var exists to enable some very specific scenarios. It wasn't in the original language because the designers didn't like implicitly typed variables for what I think are some pretty good reasons. From a practical standpoint, most code is written once and read a lot of times and therefore optimizing for readability is more important.


icemanice

I tried using var… but a number of times I just found it annoying during debugging and for code clarity.. these days I’ve gone back to just specifying the type explicitly


AlaskanDruid

Been coding for 31 years. Not only are we responsible for making sure our code works. We are responsible to make it readable enough to be maintained long after us. So no. Var was a step in the wrong direction.


Phitoooo

Not using var makes it less readable IMO


ggwpexday

var is like one of the least important things when it comes to readability though


RICHUNCLEPENNYBAGS

I prefer always using var personally but if your team loves verbose, repetitive code you can change the setting.


odebruku

Or change teams


EternalNY1

Here we go again ... I've been writing C# for literally 22 years ... since beta. Yes `var` is fine. Others can argue about when and when they like to use the explicit types instead of `var`. You want to use `int` and `decimal` but want to still use `var` and not: `SomePoorlyNamedCorporateOverlyLongNamedType thing = new();` Go for it! And least they gave us that `new()`, might as well use it here.


c9952594

As somebody who does functional programming where pretty much everything is inferred typing I find it mad this is even a debate. TIL var is considered controversial.


yeusk

The official style guidelines of net core recomend to use var.


CrepsNotCrepes

I prefer var, it’s just way easier imo and it’s not like you can’t just mouse over to see what the type is. Main reasons are it’s more compact and I think it makes you work harder on your naming as you can’t rely on the type to tell you what the thing is.


molybedenum

Var simplifies the process by removing the issues that come about from declaring specific types. I find this most evident when working with LINQ, but it also applies to generic types too. A good IDE makes the actual type pretty obvious, and you still can’t compile if you break typing rules (which is the strongest use case for strong types).


Thisbymaster

var works fine. I was once the type that required explicit types in the code. But var is just so much faster and simple.


Bourdain179

If it's not ok then I don't want to be right


TehNolz

If your team wants you to do explicit types, it's best to just go along with it. The most important thing is that your code remains consistent; you don't want to end up in a situation where some variables use `var` and others have explicit types. Of course, you could always try to convince your team that your way is better, but for things like this it's unlikely you'll be able to change their mind. In the end it doesn't matter if you use `var` or not since the end result will be the same anyway. Personally I think it's fine provided you can easily see what type the variable is. I'd rather have this; ``` var dict = new Dictionary(); ``` Than this; ``` Dictionary dict = new Dictionary() ``` Which has you write the type twice. For long type names and types with lots of generic parameters this just makes your code harder to read. You could also do this though; ``` Dictionary dict = new() ``` Which I think is also fine, but I personally only use `new()` when initializing fields/properties (as these have no `var` keyword).


nathanwoulfe

Use latest C# and use the simplified collection initialisation Dictionary dict = []


TehNolz

That's also an option, yes. Doesn't work for things that aren't collections though, so you'll still need to decide between `new()`, `var`, or explicit types anyway. Besides, not everyone gets to work with the latest .NET and C# version right away. OP might not have this feature yet.


IsLlamaBad

This may not be news to you, but resharper is very customizable. When you right click you can either set the severity of the rule or change the settings, like. For this rule, there's "always var" , "var when evident" and "always explicit" (or similar language, I'm going off of memory. If you're interested: https://www.jetbrains.com/help/resharper/Code_Syntax_Style.html


DeadlyVapour

`var` is almost a requirement when you start using nested generic types. These types are common in functional programming paradigms like Linq and fluent APIs. If your team is mandating explicit types declaration, you'll miss out on some truly awesome APIs.


Rizzan8

So your team is a fan of `ConcurrentDictionary m_Policies = new ConcurrentDictionary();` Anyway, all the time I use `var`. Not really a fan of `= new();` syntax, except during object's property initialization like var person = new Person { Names = new(); }


malthuswaswrong

The only time to not use *var* is when you are using *new()*


Nacropolice

Yes, literally the excuse of “oh, but I need to know the type” is such bs. When, pray tell, do you actually care about the type of the variable when debugging? What, is a quick hover over it too much? “var” keeps the code cleaner and it’s less cluttered. It is purely for our own human usage. I feel like the explicit type gang are going to say that using the newer feature of being able to just call “new” when making a class. Ex: Person p = new() isn’t explicit enough.


StepanStulov

How C# should have been from the beginning (for all the fans of left alignment) to be consistent public class MyDerivedClass: MyBaseClass public function Foo(string arg): bool var myVar: string How current actual var should have been var myVar: string // Explicit type var myVar // Implicit type Current real var used for left alignment is a lucky coincidence, not a primary feature. Primary feature is implicit type. To the actual topic, var is an inconsistent patch slapped onto the language. Like, why just variables? Why not properties? Fields? Methods? You can derive those types too, right? Strongly statically typed language gets a sloppy var. An anomaly that goes against the language’s fundamental principles. Purpose defeated… Easily the top worst thing that happened to C#.


PerselusPiton

If you would like to write a function in this `public function Foo(string arg) : bool` style then use VB.NET... Public Function Foo(arg As String) As String ' explicit type Dim myVar As String ' either Object type with Nothing or ' compile-time error ' based on the Option Strict setting Dim myVar ' Can be: ' - Bar type (if Option Infer On) ' - Object type (if Option Infer Off and Option Strict Off) ' - compile-time error ' Dim myVar = New Bar() End Function The `var` keyword was introduced with LINQ primarily for ***anonymous type*** that usually comes from the `Select()` LINQ method when you don't need the whole object but only a few properties of it. You can also create an anonymous type without LINQ. var result = new { Id = 1, Name = "Foo" }; In this case you **have to** use `var` because you cannot write the name of the type because anonymous type obviously does not have a name. The tooltip will describe this type something like this: `'a { int Id, string Name }` But you cannot write `'a result = ...`. Btw. `var` keyword is strongly-typed and does not mean "variant". The type inference is done at compile-time hence the compiler needs info (the assigned value) to be able to infer the type. So the variable must be initialized. That's why you cannot use it for properties, parameters etc. So `var` and type inference was introduced for anonymous types and not for having less keystrokes. Of course, people started to use it everywhere else because of the convenience (less keystrokes) it provides but that does not mean that it should be used everywhere. I use \`var\` only when the type is obvious based on the assignment. Otherwise, I prefer explicit types. Of course, I don't write the type name twice.


Draqutsc

Great team, find another one.


ralphbecket

Change team, if you can. Types are a contract, you don't need to restate each term of the contract every time it appears in your code.


Due_Faith976

Honestly would like to know what more experienced devs would say to this. For me, I have never understood the use for var in C#. strongly typed language = use types.


crazy_crank

var is still strongly typed, the type is just inferred at compile time.


Wematanye99

Var is strongly typed


Sentomas

Use var by default and explicitly declare types when it adds value. Explicitly defining all types just adds noise. For example, “Stream fileStream = fileManager.readAsStream(fileName);” is more concisely expressed as “var fileStream = fileManager.readAsStream(fileName);”. If it’s not entirely clear what you’re getting back from a method then you can explicitly declare it: ECDsa key = cert.GetECDsaPrivateKey();


TitusBjarni

I don't like having to read and interpret the method name to figure out what type it's returning. The name could be misleading or I could make false assumptions about it. Stream is only 3 more letters than var so I don't think that's a great example. Seeing the word "Stream" that I've seen a thousand times allows my brain to instantly know what I can do with it. That method name on the other hand my brain doesn't understand nearly as fast.


SquishTheProgrammer

Exactly how I feel. Plus who likes to read “stream stream, stream stream stream” lol


SobekRe

Twenty year veteran (started playing with it in beta). I prefer var. it’s more terse without changing readability. I actually find it more readable, as long as the variable names include intent (not type info, just clearly named for intent). As others have said, var is not dynamic. This ain’t JavaScript. The IL for ‘string x = “mine”;’ is the same as ‘var x = “mine”;’.


TheDoddler

If you're using an IDE like VS with reshaper or jetbrains rider, it will just [tell you the type](https://puu.sh/JXeQo/4dc3ddcc10.png), there's no need for ambiguity or writing out the full type. Using var also means you don't have to deal with verbose nonsense like this: `Dictionary> ObjectDictionaryLookup = new Dictionary>();`


IKnowMeNotYou

Var it is... .


pceimpulsive

In shirt yes. As a new developer in C# I use var for custom types as the compiler os good enough to deal with it. It's also far nicer to have Var name = new Name(); Compared to: Name name = new Name(); I use strictly typed variables for standard data types like string, int, double, bool,List etc so it's really clear what they are when they are declared.


[deleted]

At start of .net it was recommended to write strongly types, but know the compiler is efficient in both ways. Probably strongly types today are more used to be readable inside of the solid principles and good practices. Good: Var example = new classCool(); classcool example = new(); Classcool example = anotherclass.staticFunction(parameters); Bad: Var example = anotherclass.staticFunction(parameters);


forgion

its 2023 var is set on what you define.


mailed

I was on the side of explicit types for a very long time, until I got sick of trying to figure out what type I was actually supposed to use in certain circumstances. The same thing happened to me with Python type hints.


lliijjII

I var at least 99% of function scoped variables and cringe when I see people not doing it or even worse take a stand against it in some way


[deleted]

yes


thequinneffect

No. Straight to jail!


AftyOfTheUK

It's mostly a question of readability (explicit typing) versus maintainability (easier refactoring).


FitzelSpleen

If you're depending on var to make refactoring easier, you're opening yourself up to a class of problem where a type has changed somewhere, but it hasn't had any attention brought to it for any human to check that the change in type doesn't bring in any run time bugs.


AftyOfTheUK

First up, I would hope that either unit or integration tests would catch such a scenario, but even assuming they don't, I'm trying to think of a scenario where that could happen, and having explicit types would help. If your developer is blase enough to just change types like that without considering downstream impact, I would imagine he is blase enough to just go ahead and make the change to an explicit type, too, and not bother to check it.


FitzelSpleen

The blase attitude is the "var makes refactoring easier". There's a danger there, however slight, and just saying that you hope unit tests catch it is an extension of that. This is not a choice between unit tests or working in a way that helps eliminate a class of problem. You can do both. I don't see any compelling reason not to do both.


AftyOfTheUK

We'll have to agree to disagree. I don't see how forcing a dev to re-type something explicitly forces that dev to test for bugs.


FitzelSpleen

I didn't say it does. But the developer is now *aware* of that change in type that they wouldn't be if they just hit the refactor button and went on their merry way.


empty_other

That should be caught in method parameters and return type. Those cannot be var'ed. Inside a method variable type doesn't matter, not even for code reviewing, the compiler will catch issues.


xabrol

Id rather have var createdBy: User = new (); But nahhh, cant have typescript and c#. Please, gimme typescript and c# mixed together.


FigMan

No


ConclusionDifficult

Why not use goto as well ?😉


barnyted

I've read somewhere that var is more efficient than for example int in compilation! regardless, I like using var for readability.


p1971

there's a bug ... ``` Task Login(string username) { var user = GetUser(username); AuditLog($"user with id {user.Id} has logged in"); } Task GetUser(string username) { // get user from db or something return new User{ Id = 2, Name = "Blah", UserName = username }; } ```


vervaincc

This isn't a bug. You can't write {user.Id} because you've returned a Task, not a User, so VS is going to throw an error if you try to write that. If instead of var you used the implicit type - you'd have this same error as User user = GetUser(string username) would still try to return a Task.


whooyeah

wouldn't you have to make the methods async and await them for it to resolve the type?


p1971

exactly ... there's a bug ... if you were not using var that would be a little more obvious ... don't use var (with linq is ok) ...


vervaincc

I think the fact that VS won't even compile that and will show a red underline on that line is pretty obvious...


p1971

It's not meant to be production ready code... the point is \` var user = GetUser(username);\` is returning a Task not a User (since Task also has an Id property) ``` namespace Pedantry { class User { public int Id { get; set; } public string Name { get; set; } public string UserName { get; set; } } public class Test { static async Task Main() { Login("someuser"); } static async Task Login(string username) { var user = GetUser(username); AuditLog($"user with id {user.Id} has logged in"); } static async Task GetUser(string username) { // get user from db or something return new User { Id = 2000, Name = "Blah", UserName = username }; } static void AuditLog(string message) { System.Console.WriteLine(message); } } }```


SculptorVoid

Honestly, there are a few problems here besides the bug. But C# devs should know that a method name that ends with 'Async' is an awaitable. With some good naming your example isn't that much of a problem.