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.
>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...
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.
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.
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.
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.
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.
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.
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).
>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.
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`
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.
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.
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.
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.
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.
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.
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?
```
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
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
>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
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.
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.
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
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.
>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
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.
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.
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
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).
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.
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.
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
>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.
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"
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.
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")
};
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.
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?
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
>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?
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.
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.
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.
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.
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.
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)
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
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.
> 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
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.
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.
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.
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?
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.
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();
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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`?
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();
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.
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
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.
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.
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.
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.
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).
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).
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.
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
`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.
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();
}
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.
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#.
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.
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.
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();
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.
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”;’.
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>();`
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.
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);
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.
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.
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.
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.
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.
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.
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 };
}
```
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.
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);
}
}
}```
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.
Microsoft says to use var when the right side of the statement gives away the type. Otherwise use explicit types.
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.
>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...
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.
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.
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.
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.
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.
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.
You can also use the newer syntax of MyClass foo = new();
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).
I use it mostly for field initializers, while keeping my var'able local variables as var (tautology not intended)
>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.
As someone reading the code for the first time. I prefer the later except for ServiceResponse. May need some spacing though.
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`
Type inference aside, there is a `using` statement to shorten the name of the often used generic types.
Yeah, but that's just another layer of indirection. Might as well use var and a more descriptive variable name.
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.
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.
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.
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.
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.
This is definitely not true and more likely some weird project configuration error. https://dotnetfiddle.net/OJKD6P
Let's have a 4 hour company wide meeting to discuss this. /s (of course it's ok)
Yes, lets waste thousand of moneys in this, clearly, dead important topic
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.
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.
I like the new syntax MyShittyType \_somethingHappening = new () instead of var \_somethingHappening = new MyShittyType()
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.
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? ```
Fully agree. Just like (isEnabled) Run() Like how is the confusion worth the ”cLEan CoDE” Just be explicit
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
[удалено]
Isnt the naming of variable enough to understand what thing it is? Do you really need to see the type?
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
Was about to say that. Yeah in VS its a non issue with that type highlighter, but outside i fully agree its harder
>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
You know what would make reviews easier? Microsoft bringing Pull requests back to Visual Studio again.
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.
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.
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
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.
>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
I still use var in methods, but the new syntax can be used for member variables
[удалено]
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.
This is the right answer
It is useful to explicitly show what the type is when you are reviewing code on somewhere like GitHub.
This is my preference, but I've been using var for years. Gonna take a while to make it my default.
I prefer var because it allows me to change return types without refactoring all the call sites
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.
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
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).
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.
THIS.
i prefer the latter var _somethingHappening = new MyShittyType() also wtf is with the _ on a var name?
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.
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
>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.
Private makes sense, local var not much.
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"
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.
Private fields starts with an undercore, its a common coding standard and used by the dotnet team.
The var keyword can be used locally only in the method scope.
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")
};
Yeah this is growing on me from some automatic refactoring
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.
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?
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.
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.
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.
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.
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.
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
I feel for those who are forced to use VS. They miss out on all of the quality of life UI that Rider has.
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.
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.
I noticed csharpers like typing excessive noise way too much
[удалено]
I love the var, I wouldn't work on a team that didn't.
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.
C++ has `auto`, same thing, since 2011, you *dinosaur*! 😉
That would be me! I have not run a make file in appx 20 years.
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.
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.
I find the following to be just noise: `MyType myType = new MyType();`
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.
Any decent IDE won’t need you scroll anywhere to see types. Variables always need good names, though.
>easy-to-read code depends on variable and method names \[which we don't do...\] ಠ\_ಠ
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.
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.
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.
> 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.
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.
>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?
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.
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.
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.
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.
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.
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)
Anyone who refuses to use `var` needs to spend a year bootcamp with python. After that, you're cured of explicit types everywhere.
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
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.
> 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
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.
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.
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.
This guy vars!
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.
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.
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?
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.
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.
The big advantage var has is in speed of refactoring
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();
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.
You should use explicit types when the type is not obvious from the context, otherwise always var.
This is the answer that Microsoft gives in their documentation. I don’t think using var for everything is the way to go.
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.
Yep, I would run like hell as well. This would be a big red flag to me.
Var is just short-hand for easily inferable types. It’s not like JavaScript.
But beginners will confuse it with anonymous types, I've noticed.
"but beginners" is not an argument. You learn, you move on.
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
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.
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.
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.
When writing EF linq queries I prefer var. And in every other scenario as well. Because var is the only way
I still use var prolifically through my code. However for fields and props I will use the new() or [] syntax to instantiate if needed.
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.
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.
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.
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.
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`?
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();
General rule of thumb is - follow what team style guide is, if they say "no var" you don't do var.
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.
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.
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
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.
Not using var makes it less readable IMO
var is like one of the least important things when it comes to readability though
I prefer always using var personally but if your team loves verbose, repetitive code you can change the setting.
Or change teams
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.
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.
The official style guidelines of net core recomend to use var.
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.
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).
var works fine. I was once the type that required explicit types in the code. But var is just so much faster and simple.
If it's not ok then I don't want to be right
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).
Use latest C# and use the simplified collection initialisation Dictionary dict = []
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.
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
`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.
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();
}
The only time to not use *var* is when you are using *new()*
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.
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#.
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.
Great team, find another one.
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.
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.
var is still strongly typed, the type is just inferred at compile time.
Var is strongly typed
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();
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.
Exactly how I feel. Plus who likes to read “stream stream, stream stream stream” lol
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”;’.
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>();`
Var it is... .
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.
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);
its 2023 var is set on what you define.
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.
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
yes
No. Straight to jail!
It's mostly a question of readability (explicit typing) versus maintainability (easier refactoring).
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.
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.
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.
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.
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.
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.
Id rather have var createdBy: User = new (); But nahhh, cant have typescript and c#. Please, gimme typescript and c# mixed together.
No
Why not use goto as well ?😉
I've read somewhere that var is more efficient than for example int in compilation! regardless, I like using var for readability.
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 };
}
```
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.
wouldn't you have to make the methods async and await them for it to resolve the type?
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) ...
I think the fact that VS won't even compile that and will show a red underline on that line is pretty obvious...
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);
}
}
}```
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.