Why Do C# Developers Hate The var Keyword?

2024 ж. 3 Қаң.
60 484 Рет қаралды

Use code MICRO20 and get 20% off the brand new "Getting Started with Microservices Architecture" course on Dometrain: dometrain.com/course/getting-...
Become a Patreon and get special perks: / nickchapsas
Hello, everybody, I'm Nick, and in this video, I will talk about one of the most debated topics in C# and that is the use of the var keyword.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elfocrash
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер
  • I love how the var keyword forces me to think about how I name things. That explicit type isn't there a few more lines down where it is used. Having the variable named appropriately helps in many ways, and using the keyword facilitates that.

    @logank.70@logank.704 ай бұрын
    • i really cant agree with this as variable name and variable type have two entirely different purposes. Type is needed for the 'debug' problems, meanwhile name is needed for the program's.....Buisness level problems (i think the best word i can use here but there might be something better) Mixing them im not sure is a good approach.

      @StarfoxHUN@StarfoxHUN4 ай бұрын
    • ​@@StarfoxHUN This is somewhat an agreement with Starfox, but also possibly a tweak for logan. I feel empowered to use the `var` keyword because it forces me to think about how I name METHODS specifically. I can't stand seeing people naming methods like `doThing` or `get`. If the method signature is `GetUser(int id)`, then it is easy to know that `var whatever = GetUser(5)` means. On the other hand, as per starfox's point, why not have `User whatever = GetUser(5)`? Well that's fine. The only issue (prior to 2 years ago) was this: Dictionary mySomething = new Dictionary(); Obviously that would be better as: var mySomething = new Dictionary(); Or, as of 2 years ago, it is now fine to say: Dictionary mySomething = new(); But the new() way only solves half of the issue. In my opinion, it is still Double-Declaring (or triple) types like this: UserEntity user = new UserEntity(); // why? The value of `var user = new UserEntity();` is that, if I see that I can make better use of an ACL/DTO layer, and I should be using the UserModel, then I change it in one place: var user = new UserModel(); The rest of the code should work, never see a squiggly line. This seems pretty basic, but think about it more like this: UserEntity user = GetUser(5); If the type of `GetUser` changes to `UserModel`, then you have to go to a lot of other places to make changes. Of course all of this is moot in the end with the "Refactor Method" ability (I assume), and with the `new()` ability. So nobody really cares? Edit: ((Lol, just started watching the actual video after typing all this, and hilarious that Nick is using `User` as examples.))

      @JinnFletch@JinnFletch4 ай бұрын
  • I love the alignment of the variables names with var. I think that makes the understanding of the code easier, but only if the variable names are expressive of the content or scope they mean.

    @t-moty@t-moty4 ай бұрын
    • even if all the variables where of the same type (same character length) at a certain length of the block it would be just as hard to read. the entire reason for var is to avoid a C/C++ situation of "dumb conversions at declaration" (because in C/C++ you have explicitly declare how that conversion works) At one point in a C# preview compiler on a declared `var` would wait until the first use to do "figure out" the conversion if there was not an explicit assignment operator, and if someone came in and changed the first operation the initial assignment conversion would be different and now even the expressively named variable has the wrong type. the operations might all be valid and the results similar, but the JIT is doing extra conversions from the wrong type.

      @gardian06_85@gardian06_854 ай бұрын
    • The question is whether you want your code to look nicely symmetric with a ton of var keywords, or if you want your code to be actually meaningful and understandable at first. This was, after years of moving back and forth (also see my other comment), a reason why I now prefer more explicit types, and follow Microsoft advice. But that's in C#. I also write Rust, which has type inference all over the place, far beyond C# capabilities. But there it's all type hints of the analyzer in the editor do the rest of the work. You can use explicit types, trailing behind the variables, and in a small part of the situations you need to add these, but I really rely on inference most of the time. C# never got those type hints, and is a different language with different needs. So I kind of accept that difference.

      @jongeduard@jongeduard4 ай бұрын
    • @@gardian06_85 The entire reason for var is to support anonymous types, especially those created with LINQ.

      @kaufmed@kaufmed3 ай бұрын
  • Using explicit type only helps at the point of declaration, while proper naming helps everywhere. I prefer to have self explanatory variable names.

    @Hunpriest@Hunpriest4 ай бұрын
    • need both imo.

      @mrx10001@mrx100014 ай бұрын
    • Names won't always encapsulate all the useful information you would get from an explicit declaration unless you use Hungarian notation or something

      @arielkoiman4509@arielkoiman45094 ай бұрын
    • knowing the type at the point of declaration is pretty important, unless there is good IDE support

      @xybersurfer@xybersurfer4 ай бұрын
    • ​@@xybersurferSince when DON'T we have helpful IDE support!? Seriously, this is all a storm in a very small tea cup! But then, software developers are a pedantic lot! Some... More than others!

      @sdwone@sdwone2 ай бұрын
    • @@sdwone i agree that it's pedantic (or at least vague). there is usually no problem with IDE support in C#. i was thinking more in general about dynamic languages. in my recent experience with Python i was typically missing IntelliSense, which did not always work in combination with it's multiple half baked competing Type Hint formats (which tries to introduce types). in my comment i was trying to imply that not all languages have such good IDE support as C#. but i typically don't like seeing Hungarian Notation as the thread starter suggests. i prefer meaningful variable names

      @xybersurfer@xybersurfer2 ай бұрын
  • I use 'var' most of the time. It feels more aligned, and I also make sure to name the variable properly in terms of context so that code readability is enhanced.

    @persiansayed@persiansayed4 ай бұрын
  • I'm absolutely baffled that you didn't talk about the value of var when refactoring. I work in old legacy codebases with dozens of projects. And if you use var, then when something is getting renamed, it can drastically reduce the amount of places you have to go change just to change the type. Splitting up interfaces and renaming them - you need to change a much smaller subset of code if you're using var. And when it comes to the "i want to know what class it is" argument, i gave up on that years ago. The reality is, i called a method and got a thing. what kind of thing? who cares, its a thing

    @danielprows6416@danielprows64164 ай бұрын
    • I wrote my comment and then saw yours. Had the exact same experience when refactored legacy code. Also agree with "I got a thing". It's not like if I see the class name "PaymentDetails" instead of var I would necessarily know what it contains. I would have to go in any way, or use the context ahead to figure out the usage.

      @alonmore28@alonmore284 ай бұрын
    • Oh yes, TFW you have to wrap the return type of some method into another type (into Either for instance) and now you are facing 1234 errors just because someone didn't use `var`

      @user-tk2jy8xr8b@user-tk2jy8xr8b4 ай бұрын
    • On the other hand, those errors point you to places where additional checks are needed anyway. What if the old and new return type share a method in name that absolutely shouldn't be called where it was called on the old type? I don't mind the errors at design time if it means less errors at run time.

      @epiphaner@epiphaner4 ай бұрын
    • The other side of that argument is that using 'var' means that you might not REALIZE that you're changing something with an effect somewhere else, and nobody reviewing a pull request will see those hidden changes either.

      @doom-child@doom-child4 ай бұрын
    • @@doom-child right, there are certain cases when leaving an explicit type makes sense, at least until C# gets a type ascription syntax

      @user-tk2jy8xr8b@user-tk2jy8xr8b4 ай бұрын
  • the situation in which I really hate var is when I forget to type "await" and end up with a Task instead of the T I expected. Especially bad when my T had a .Result property that the compiler confuses with Task.Result

    @LCTesla@LCTesla4 ай бұрын
    • This ☝️

      @lahodal@lahodal4 ай бұрын
    • so true

      @memes_gbc674@memes_gbc6744 ай бұрын
    • This is one of those things where I don't do it often, but when I do it takes forever to figure it out.

      @sliderhouserules@sliderhouserules4 ай бұрын
    • This is so easily avoided with static analysis though. In fact I’m pretty sure in visual studio, calling an async method and not awaiting it results in a compiler warning.

      @bass-tones@bass-tones4 ай бұрын
    • Good IDEs will pick this up! I mean Visual Studio is pretty good at this! And these IDEs are getting better all the time! So let them do their job, so that you can get on with the actual coding!

      @sdwone@sdwone2 ай бұрын
  • The rule I have always followed is "use var unless the output type is not obvious". It comes down to developers understanding your code. You could use var everywhere but it might make some code appear ambiguous. So, be as clear as you can within reason.

    @arztje@arztje4 ай бұрын
    • Tbh being as clear within reason is using "var". You can always hover over the variable to know which type it is, which is faster than, say, ctrl click to go to where it's defined. There shouldn't really be any debate, but what can you say.

      @parlor3115@parlor31154 ай бұрын
    • This is why I love C# for this, it will either be declared in the left or in the right as new something(). So its mega easy to follow what's being made as long as the functions are named accurately. Been using golang lately and I hate how I need to constantly mouseover things to check types, because for silly reason the type is declare after the var and name... talk about pointlessly verbose.

      @mrx10001@mrx100014 ай бұрын
    • @@parlor3115 What if you are reading it without intellisense? Ex. you are performing a PR from a git repo? It should be understandable at face value without the aid of tooling to explain it.

      @arztje@arztje4 ай бұрын
    • @@arztje Then you're only going to need explicit typing when calling a method. But, if it's a method you developed or familiar with, then there's really no need to. If not, you're going to have to look up the method anyway. So, it's not worth making the code more verbose.

      @parlor3115@parlor31154 ай бұрын
    • at my company it’s more like use var when the type is ambiguous 😅

      @pascalkhoury@pascalkhoury4 ай бұрын
  • I like using "var a = new B()" more than "B a = new()" because I have always the same var keyword to the left and can read variable names quick enough to read the code faster. If it was like ReallyLongServiceName a = new(); followed by another few declarations of different length, I would need to more time

    @isnotnull@isnotnull4 ай бұрын
  • We use the `User user = new()´ at my company, and my biggest issue with it, is that sometimes the types have long names, which means you actually spend time finding the variable name. Not a long time, but it adds up. Where if you use `var user = new User()´ variable names are all in a line.. The vast majority of time it doesn't bother me much, it is mainly when i look through some startup files with a lot of config/builder/factory types, where the type-names are super long, when i get a little frustrated with the banning of the var keyword.

    @Ziirf@Ziirf4 ай бұрын
  • I use var whenever possible, especially when putting return values of Method calls into local variables. The type I'm getting back from that method might slightly change, even though the semantics can still work. For example someone did a refactoring in the project and renamed the type. Without var that would cause a MASSIVE diff because the type name changes for every use everywhere. If however var is used, the diff is nice and clean. IMO that's the most important reason to use var. I never understood why people insist on the concrete type anyway. Your variable names should be well chosen so the type should be easy to guess already anyway, and if you need more information... the IDE will give the type to you if you simply hover over the identifier. Var exists for a reason, typenames are pointless in code. if someone needs to see the types to understand what the code is doing, then that someone needs to start writing better code.

    @LeutnantJoker@LeutnantJoker4 ай бұрын
    • It's simple. If one needs to see the type, then in most cases the naming is just bad.

      @VoroninPavel@VoroninPavel4 ай бұрын
    • Ull output somehting that also has .settings No errors, Compiles BUT new code doesnt work. hmm. why? Well cos no type, and both types have .settings but u forgot to update new type.settings to new values. So now ur whole system broken. GL fixing it XD

      @cybertpax@cybertpax4 ай бұрын
    • ​​@@cybertpax That kind of sounds like the refactor-ers fault more than anything else. If you're changing the return type to something different and not seeing errors AND not bothering to check any references for either the method or the .settings property (the thing that is explicitly incompatible with previous logic) then what do you expect to happen? "Oh I changed this to something completely different but it still compiles, this is fine" Edit: but yes, using explicit typing would 'avoid' this by forcing you to update the call site everywhere, everytime

      @lordshoe@lordshoe4 ай бұрын
    • @@lordshoeBecause different people work on different part of code and you can't rely on people to keep track of every single function call and check if they have call the function. Having explicit type will produce comiple error and force the developers to check explicitly.

      @cwingnam@cwingnam3 ай бұрын
  • When var was introduced I was of the opinion that you should be able to see the type. Then I started to use var everywhere and generally think that having the explicit type is only really useful in a handful of cases. Now with the new 'new()' expression and the new collection literals '[]' I am switching mostly class members to use that syntax. I still like using var in function body code - even when it is a bit longer... (I think a developer should not complain about something being longer or shorter tp type. Readability is king - however many characters it takes)

    @obiwanjacobi@obiwanjacobi4 ай бұрын
    • I think a developer should really complain about something being longer or shorter to type, I've been programming for years continuously and my hands are in pain nowadays, the less you write the less it stings. And the readability is obviously a target when programming, but you can write short AND readable code, there is not a contradiction between these two. Var will not make your code less readable, if it not makes it readable due to less visual noise it will at least not hurt, and the type hinting can show you the implicit types for more correctness.

      @diadetediotedio6918@diadetediotedio69184 ай бұрын
    • @@diadetediotedio6918 I agree on that the readability is not really affected by var. I very rarely need to know the actual type of a variable, in most cases its either obvious or I only need to know the type if I fail to find the property I was expecting. And the variable declaration is rarely the easiest place to look since even for medium size methods that would need me to look further up the screen, using hover lets me keep the focus on where I am and for a longer method looking up the declaration could mean scrolling which is way worse. Sure "you should use short functions", but that rarely holds true for bigger projects over many years and many different developers and different libraries ;)

      @davidmartensson273@davidmartensson2734 ай бұрын
    • ​@@davidmartensson273from my experience, a big procedure is always bad evenire in big projects. I became a no nester before I knew the term because big means not maintainable for various reason (it leads to copy paste code, bad optimisations, difficulties in maintenance...). So using var isn't a big deal. However, now that new() exists, i do prefer that syntax.

      @warny1978@warny19784 ай бұрын
    • The new new() syntax is cool, but I have found it now takes longer to find all places where a class is instantiated.

      @br3nto@br3nto4 ай бұрын
    • @@warny1978 I agree, but in a 10+ year old code base created by 30-40+ different people you will have them :) And in some cases like long switch statements you cannot really avoid a long method as splitting the switch costs. Same thing with many other cases especially when you have an opinionated e-commerce platform as a base you cannot escape. Sure for new, smaller projects I really do keep methods small, but then its even easier to keep track on types without explicitly stating them :) Sure if I find some hard proof that using explicit types improves something I would use it but having used C# since before var I se no reason to change now :)

      @davidmartensson273@davidmartensson2734 ай бұрын
  • Visual studio has a feature that shows inline hints about types and parameter names. It can be either kept always on, or activated when pressing Alt+F1. It's useful because it allows me to use the var keyword even when the type can be ambiguous. Anyway I do like the newer syntax and i tend to use that when possible

    @CristianBaldi@CristianBaldi4 ай бұрын
    • I think the problem is with code review or devs that use notepad

      @zoiobnu@zoiobnu4 ай бұрын
    • I think this is the best answer. It caters to all preferences. You like var? Fine, use var. You like explicit types? Fine, turn on the IDE hints. Everybody happy.

      @sanderschutten@sanderschutten4 ай бұрын
    • You beat me to it!! This feature changes the arguments in my option

      @talyrond2047@talyrond20474 ай бұрын
    • @@sanderschutten Except now when you have that enabled the code shows both the var and the type name, making it much more busy and cluttered. I tried using that option for a while but turned it off because it was just getting in the way.

      @djp_video@djp_video4 ай бұрын
  • I use `var` in nearly every situation. There are a few instances where it's obvious that adding a type will improve code readability. Nearly every C# developer uses an IDE or code editor that provides intellisense or something similar. If the developer is confused about the type of a variable, they need only ask the tool for they type, usually by just hovering the mouse cursor over the variable.

    @JasonStoudt@JasonStoudt4 ай бұрын
    • Yeah, make your tools work for you, not the other way around.

      @MrTerribleLie@MrTerribleLie4 ай бұрын
    • Yup exactly, and in a lot of cases got can tell by the initialisation any way - " var thing = false:" pretty safe bet that's a bool!

      @JetsetDruid@JetsetDruid4 ай бұрын
  • You should consider what happens when someone refactors some code. If a method's return type is changed, the code catching it with "var" may still compile without warning. It if was explicitly typed it will not compile. It depends on what sort of behaviour you think is better.

    @vonn9737@vonn97374 ай бұрын
    • I was about to say this. Sometimes if I'm refactoring and I want to know exactly which parts of the code I'm touching during the refactor so I can spot-check for breaks, having var spread throughout the codebase can make that difficult because untouched parts of the code may still appear to compile fine even though the underlying types have changed

      @silentdebugger@silentdebugger4 ай бұрын
    • I fully agree!

      @Emelion1@Emelion14 ай бұрын
    • That would also mean that the code that makes use of the var uses the same properties, passes it to the same methods as before, all without hitting a compiler error? And then have it be considered a bug? I would really consider the thing that the code is doing then, besides this being such a far fetched situation that it's not worth being explicit for imo.

      @z0nx@z0nx4 ай бұрын
    • @@z0nx Example: private readonly List _registeredObjects = new(); public void Cleanup() { foreach(var subObject in _registeredObjects) { if(subObject is MyClearableSubObject clearableSubObject) { clearableSubObject.Clear(); } } } Now change the List to a Dictionary because you wanted to access your sub-objects by id. With _var_ the code still compiles but does not work anymore and you might not notice, that you need to iterate over _registeredObjects.Values instead.

      @Emelion1@Emelion14 ай бұрын
    • That sounds like what find usages is for, not touching a bunch of files that doesn't need it.

      @ttolst@ttolst4 ай бұрын
  • Not a fan of "var" personally so I aim to avoid it. The new() syntax is definitely my favourite way to go with declaring a new instance of a type. I like consistency so using var in some instances and not in others just adds too much overhead to thinking about whether to use it or not, especially for a junior developer joining a project. Keeping it consistent and avoiding the use of var altogether simplifies things a lot in my opinion.

    @stephajn@stephajn4 ай бұрын
    • Yikes. Heavy disagree. new() isn’t a replacement for var, because var’s usage extends beyond constructing objects. How do you call methods? You explicitly type the return type of every method you call? Why? What’s the point in putting that type in N spots instead of 1? It’s just N more things to refactor when or if that method changes. Do you not use Linq? I’d actually argue Linq is completely unusable without var. And Linq is one of, if not the best feature of the DotNet ecosystem. Banning var completely is nuts to me.

      @bass-tones@bass-tones4 ай бұрын
  • I'm mostly with Microsoft's recommendation. But generally speaking I use explicit types to make the code easier to read. But also so it is consistent rather than switching styles back and forth. At one point I had fully embraced vars because it's so much faster to write, but in time I found it too difficult to go back and debug or modify and have switched back to explicit types in most cases. Real-world example: One of my former coworkers always wrote everything using 'var' no matter what. And I always hated trying to debug and fix her code. It could literally take hours to figure out what it was doing because she did everything with vars and [improperly or poorly named] method calls and just getting through short sections of code was excruciating and could take forever just to figure out what it was supposed to be doing. Literal hours in many cases. Whenever I have an assignment to fix something in her code (which is still far too often -- 90% of the bugs in the project are in her code), I'd change non-obvious vars to explicit types, and rename variables and methods so you could tell what they did, just so I'd have a shot at deciphering what it was supposed to be doing. But then the next time she would go into that code she'd change it back. For her to revert a commit was far more common than it should be. Incredibly frustrating. Everyone else on the team hates working in her code too -- it isn't just me. For what it's worth, she ended up losing her job, at partially over this kind of behavior. When you're working on a team you have to create code that others can read and understand and modify. But it's a good idea for your own projects too because you never know how long it will be until you have to come back in to fix or extend something. If I can't tell at a glance what data type something is, even if I can discover it by hovering over it, it is much too frustrating and time consuming to try to read and fix code. I don't want to waste time putting unnecessary thought into figuring out what data type something is, especially when a tiny change in the code can entirely prevent that. Explicit types make it much easier to see what is going on. Even with appropriately named variables and methods, it takes longer to read and follow the logic on code you aren't familiar with when it uses vars. In the cases where it's easy to tell like "var user = new User()" sure, a var is fine, but for most other situations it's just better in the long term to spell out what data type you're dealing with.

    @djp_video@djp_video4 ай бұрын
  • Hi Nick. Nice concise video worth clear arguments. Missing in your answer: coordinate with your team and help your coding tools along by codifying your standards in an editor.config file in your repository.

    @Apipoulai@Apipoulai4 ай бұрын
  • One thing I think is nice about var, is how it allows me to keep the type abstract, making it easier to change it from the source later on

    @Subjective0@Subjective04 ай бұрын
    • Code smell right there

      @mindstyler@mindstyler4 ай бұрын
  • This is polarizing and the division seems to come down to use case and experience. If you write small disposable code or simply disregard maintenance, var seems fine. If you maintain a legacy monster under quality control or have been burned by sneaky breaking changes, it will look like slop. The notion that "I can read code writen with var" as if it's some kind of special ability really just means you're comfortable making assumptions and disregarding the potential for missed breaking changes, even changes that can be expressed in behavior at run time. I use var a lot when roughing out or troubleshooting but always change to explicit types before PR. I include explicit types in style guides. It takes very little effort in VS.

    @MisterFusion113@MisterFusion1134 ай бұрын
  • There is another variation that I like to follow (and that you can configure Rider to do as well), and that is to use `var` wherever possible except for the types that have dedicated keywords and/or are intrinsic to the language. This means you'd use the explicit keyword for `int`, `string`, `bool` and also for primitive arrays like byte[], while anything else that is a custom type you use `var`. This clearly separates the custom types from the primitive "atoms" the custom types are made of, something I much rather prefer than knowing the exact type (especially when dealing with generic types). Besides, I found that in practice when I am not sure about the return type or value, I navigate to the called method on the right side of the assignment anyways because which gives me not only the full return type but also contextual information like XML documentation, other parameters passed in, and if it open source also the code implementing it etc.

    @washi_dev@washi_dev4 ай бұрын
    • Agreed! This is the convention I follow. Built-in types have no business domain meaning/value, so I like to call them out clearly when they are used as variables. I don't really care what type a variable is if it uses a custom type, as long as the program compiles and the variable name makes sense giving the context of the containing method, the method that generated the value stored in the variable, and the way the variable is used. If explicit types are so important for readability, then how do F# programmers ever get anything done? F# uses "let" for variable bindings and many F# programs have few type annotations for methods! Yet, developers appear to be productive in F# and are able to maintain F# codebases 🤔. If I refactor a C# method to return a different type and that type has the same properties and methods (maybe I replace a concrete type with an interface), not needing to go an update a bunch of type annotations feels like an example of good software design - "var" supports this story. This discussion/debate, in my opinion, is less about the right/wrong approach and more about comfort/familiarity. It's fine to discuss/debate a preference that is based on personal comfort but it's hard to argue from position and convince people... hence why this discussion is still going on years later 😁.

      @seangwright@seangwright4 ай бұрын
    • Totally agree on this one!

      @plaam@plaam4 ай бұрын
  • In typescript and rust, developers prefer type inference over explicit typing. It's less typing, makes code easier to read and if you want to know the type you can just ask your IDE.

    @Brad_Script@Brad_Script4 ай бұрын
    • How do you ask a web interface where somebody might be reading your code (e.g. GitHub)? And should we be optimizing for writing code, or for reading it?

      @doom-child@doom-child4 ай бұрын
    • ​@@doom-child I'd say checkout the code and review it in a proper editor/IDE, why would you optimize for reading it in a web interface? Isn't the goal to write code, not essays?

      @generic_programmer@generic_programmer4 ай бұрын
    • @@generic_programmer I disagree with your basic premise. Abel and Sussman wrote “Programs must be written for people to read, and only incidentally for machines to execute.” And Martin Fowler wrote “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” If you prioritize writing code over reading it, you have more trouble getting people to interact with your code (or worse, they break things easily because they don't understand the code). Remember, you write code once, but it potentially gets read many times. As to just checking out the code, what if they're browsing on a phone or tablet? What if they're in a situation where they don't have the resources or time to open a full-blown IDE just to look at a one-page pull request? What if they use a different IDE, a different version, or a different configuration that doesn't present that information easily or at all? If you're depending on anyone who's going to interact with your code to have a specific set of tools, you're locking out (or hindering) anyone who doesn't have that same toolset and configuration. For some projects, that might be reasonable, but it's not something you should do without being VERY aware of the consequences.

      @doom-child@doom-child4 ай бұрын
    • @@doom-child Reading. Inevitably someone (including you) is going to have to go back in and figure it out again at some point.

      @djp_video@djp_video4 ай бұрын
    • @@djp_video Exactly. You start out assuming that readability is the important thing. Maybe there are a few places where performance demands less readable code, so you change those, but you always take reading as the default priority. Someday, you will thank yourself when you're back inside something you haven't thought about for a year and a half.

      @doom-child@doom-child4 ай бұрын
  • I've always encouraged my teams to follow the example you reference from the detroitaquaman comment. If it's on the same line it is obvious and doesn't require intellisense to reveal the underlying type. When it isn't obvious, I like to make it clearer by using the explicit type.

    @darryltaylor9282@darryltaylor92824 ай бұрын
  • Thank you Nick! That was very informative.

    @torrvic1156@torrvic11564 ай бұрын
  • I'm with microsoft on this. If the right side doesn't make it obvious what type it is then I don't use var. The exception is readability. Sometimes the type can be just inconveniently long and make the code a lot less readable. Dictionary as a random example that I just made up is not going to improve how rapidly you can read and understand the code. It's better to just use var and then get the specifics from the tooltip when you need them.

    @cew182@cew1824 ай бұрын
  • Thanks for the great video Nick!!! I too think much like you, I pretty strictly use var in the methods, unless I need to create a variable of a type that I am not initializing until further down the code (aka a switch block that will change the value based on a condition). I have been using Rider for many years, and love the `var` keyword. Of course stuff like creating properties you still need to use explicit declaration. I have had this exact debate with friends, and I completely get both perspectives. You hit the nail on the head with context, and 'use your brain' comment. and with the introduction of the collection initializer `[]` Rider will also recommend that over say `new List();` initialization, and it makes sense to explicitly type your variable for those cases too. I have used Rider for years and generally follow their 'recommendations'. I believe much of this topic comes down to the IDE of choice (and it's opinionated settings) along with level of experience, and quality of code.

    @amurray04@amurray044 ай бұрын
  • I use it every single time. Some people just need something to hate. C# is strongly typed, no error can happen

    @imhassane@imhassane4 ай бұрын
    • And for the people that say "it makes the code less explicit and more prone to errors and confusion", there is a funny concept called 'type hints' in which your editor shows the type for you when you use'var'. Unless you are coding on a literal notepad this should not be a problem at all.

      @diadetediotedio6918@diadetediotedio69184 ай бұрын
    • @@diadetediotedio6918 yes I wanted to say that but maybe some use nano to write C#

      @imhassane@imhassane4 ай бұрын
  • some excellent points made. I do feel like the new feature keeping the types on the left, short-handing constructors is the most consistent.

    @utubekade@utubekade4 ай бұрын
  • I personally like the new approach and I use it wherever it's possible. It's clear and shorter. There are 2 downsides in my opinion: 1. When using the type at the beginning, and declaring a couple of variables in a block, their name may not align vertically, especially when you have a combination of short and long class names, it may introduce some eye travel in all directions :P 2. When dealing with legacy code where it's using the older C# version. Then you have no other choice to use the other 2. In that case, I use var keyword to mitigate the first problem.

    @Ali-ll7lr@Ali-ll7lr4 ай бұрын
  • I mostly use var for any other types (even built-in types) other than primitives. a) var user = new User(); b) var date = new DateTime(); c) bool isCreated = userService.CreateUser(); d) string formattedText = textFormatter.Format(text); feels more natural to me this way. I think it's more important to have descriptive variable names.

    @axelbreekweg@axelbreekweg4 ай бұрын
    • I liked this approach

      @lucasjleandro@lucasjleandro4 ай бұрын
    • Primitives are generally short enough anyways. Like int x = 3 vs var x = 3, literally same amount of characters. And you know from the start you want an int or double, so why not just write it down?

      @klocugh12@klocugh124 ай бұрын
    • @@klocugh12 Yes, also it is error prone to use something like var num = 3; because someone may accidentally change it to var num = 3.0; and now you have a double which may not be what you want here. int num = 3.0; Will be marked as an error

      @neralem@neralem4 ай бұрын
    • @neralem but by having the compiler tell you, it's a error that falls you normally into pit of success. Compiler is helping. Not your enemy. Being explicit could be helpful though: var int0 =0; var decimal0 = 0.0m; Now you need to know the notation. But also the conversion rules int int0 = 0; decimal decimal0 = 0; Could introduce boxing (even if the compiler is clever enough for constant expressions)

      @biohaz999@biohaz9994 ай бұрын
    • ​@@biohaz999 Yeah but everyone makes mistakes and I'm happy that there is typesafety and all those analyzers in C# that minimizes such. Even if there are some rare cases when I use var too, I think C# whould be slightly better if it wouldnt exist. Not so much because of what I've showed in my example, but for better readability. But that is just my humble opinion.

      @neralem@neralem4 ай бұрын
  • Love this, insane that this is sooo polarizing. I use var, and don't have trouble reading var..... I used my IDE effectively to give me more detail were context isn't clear.

    @vernonjacobs7140@vernonjacobs71404 ай бұрын
    • Yeah, this is the thing. Legacy programmers insist that everything be done as though you're writing on a Unix system using nothing but a text editor. It's a bit pointless, IMO, when you have something like Visual Studio tracking things so well for you.

      @benjamininkorea7016@benjamininkorea70164 ай бұрын
    • @@benjamininkorea7016 To be fair, when reading a PR, you often don't have your full IDE showing that code. IDEs provides great tools, but the code should be readable and easily comprehensible without.

      @kodwhat@kodwhat4 ай бұрын
    • @@kodwhatWhy should that be the case? It feels like saying I need a carbonated engine so I don’t have any electronics that could fail with EFI. I get it but at the same time I’m almost never _not_ in my IDE. And if a PR is that complex, I’ll pull the branch down and review it locally.

      @JollyGiant19@JollyGiant194 ай бұрын
  • Great video! I was told to avoid using var for a long time but I moved jobs and was encouraged to use it. I grew to really like using var, however with the new() explicit declaration, I feel like stopping. This video in particular has got me really considering it.

    @Skeffles@Skeffles4 ай бұрын
    • please leave c# OR use types.

      @cybertpax@cybertpax4 ай бұрын
  • One of the best benefits I see from using var in general, is flexibility for future refactor. For example, if you use factories and whatever the factory returns is also what is consumed in some methods, allows me to just changed the source of those types and the destination without having to touch anything else.

    @ralmslb@ralmslb4 ай бұрын
    • So you're lazy

      @MudHut67@MudHut674 ай бұрын
    • ​@@MudHut67 Yes. That's why we are programmers, be lazy and smart, that's why we make computers to do our biddings.

      @diadetediotedio6918@diadetediotedio69184 ай бұрын
    • With a refactor like this I would prefer the added caution of the code breaking, making it explicit that that code was written with a different type in mind and probably needs to be changed even if it compiles anyway

      @timquestionmark@timquestionmark4 ай бұрын
    • I also liked this benefit a lot until it came back to bite me a few times. The problem with it is when you change return types. The code is still valid and compiles but you end up with a runtime error when the contents of the var is no longer what's expected by the later code. If your casting, type checking, or something else it will either fail the check or return null and then you're left figuring out why that happened. If it had a concrete type it would have been obvious immediately while you were refactoring.

      @cew182@cew1824 ай бұрын
    • @@timquestionmark Why? If the code is wrong then it would not compile after the changes in the first place. Var is useful when you change types that are interchangeable.

      @diadetediotedio6918@diadetediotedio69184 ай бұрын
  • I can think about one simple case - you are using a library done by the other team. It returns a message as a string which you on you side logs like this: var message = 3rdParthMethod(); Log($"Message was {message}"); Now you are upgrading this dll but now it returns an object with message in property. With explicit types you have an error and you see that you need to upgrade code here. With var you will find out the bug when you will need those logs just to see there is only a class name inside... And I know - the other team introduced a breaking change. Impossible with perfect people in the perfect world isn't it ;)? So to me - if explicit types easily removes this issue - I am in favor of this)

    @Adiu72@Adiu724 ай бұрын
  • One of the most overlooked advantages to using 'var' is refactorability. It's a small annoying thing that adds up BIG over time when doing refactors. Need to change a List to a List? just change the function argument and the rest of the types in the function will update along with it if you're using 'var' consistently. Then the compiler will tell you where the type change ACTUALLY causes breakages you need to address.

    @domportera@domportera4 ай бұрын
    • This. Even the strongest point about having it explicit for pullrequests is such a non issue in my experience. And I read plenty of pullrequests from codebases that I'm not that familiar with. This is such a csharpy thing to make a point out of lol. Meanwhile the rest of the codebase is full of things like, mediator, fluentvalidation, 10 layers of interfaces and factories etc

      @z0nx@z0nx4 ай бұрын
    • ReSharper and Rider can both do this for you automatically. Also, if you're assigning a variable to a method's return value instead of, say, new List(), the type will be completely opaque to the reader until they look up that method's signature

      @arielkoiman4509@arielkoiman45094 ай бұрын
    • I never had this issue before. Not saying it doesnt exists, just wanna let you know :)

      @Forshen@Forshen4 ай бұрын
    • Ull output somehting that also has .settings No errors, Compiles BUT new code doesnt work. hmm. why? Well cos no type, and both types have .settings but u forgot to update new type.settings to new values. So now ur whole system broken. GL fixing it XD

      @cybertpax@cybertpax4 ай бұрын
    • Yup, often times finding the most abstract point in a hierarchy adds a lot of flexibility without you having to manage it.

      @adambickford8720@adambickford87204 ай бұрын
  • Just my 2 cents, I do not use var. As you explained, you can see what the variable is based on context after declaration 5:37. I want to know what it is immediately, not having to read ahead just to go back to the declaration. I just feel this is a better approach for maintainability, especially going back to code written months or years ago where you do not remember everything that happens. I must admit the new() syntax is brilliant and use it where I can

    @harrismj80@harrismj804 ай бұрын
  • Great explanation! I fully agree, with your meaning: Use var and new[] if it's clear what type will be returned. On myself I also the guy who prefers strong types but also uses both writing types (var and new[]) when it makes code better readable.

    @KarlTH2005@KarlTH20054 ай бұрын
  • I think more important, is that whatever you choose, be consistent. It adds some uniformity to the code, and makes building context easier when scanning code. Being bereft is always preferable, but some just like all the syntax (I use to be that way), now I just want to say it and be done. Be consistent, whatever you choose.

    @tanglesites@tanglesites4 ай бұрын
    • Ideally automated

      @NickMaovich@NickMaovich4 ай бұрын
  • I use both interchangeably. But honestly I just use var when dealing with really long type names like deeply nested generics.

    @protox4@protox44 ай бұрын
    • Same here, especially happens to me with ienumerables

      @timquestionmark@timquestionmark4 ай бұрын
  • yep, the "new()" syntax is the one I use all the time

    @cheebadigga4092@cheebadigga40924 ай бұрын
  • Why would someone hate it? It makes my life easier.

    @rizistt@rizistt4 ай бұрын
    • Because it makes the code more ambiguous and can lead to mistakes

      @MudHut67@MudHut674 ай бұрын
    • @@MudHut67 No, it really can't. I never had any mistake caused by 'var's, and this does not make any sense when we have type hints on editors.

      @diadetediotedio6918@diadetediotedio69184 ай бұрын
    • ​@@MudHut67 mistakes like what? Once var was introduced in C# 3.0 I have started using it right away exclusively and never ran unto any mistakes.

      @NickMaovich@NickMaovich4 ай бұрын
    • ​​@@diadetediotedio6918that just means you type slow and mouse over every variable, and don't work with complex code

      @MudHut67@MudHut674 ай бұрын
    • @@MudHut67 I guess ambiguity comes mostly from the way variables are named and lack of proper documentation. But would like to know what type of mistakes you're talking about.

      @rizistt@rizistt4 ай бұрын
  • I hate "var" because I want to know the type of the variable. I don't want to mouseover it, I don't want to "figure it out from context", I want to see it immediately. Also there is the possibility to define inherited types to variables with abstract types, where you'd have to break the "var"-usage convention anyway. I also want to enforce strict typing (when dealing with number types), so I want to be notified if something isn't as intended.

    @brianviktor8212@brianviktor82124 ай бұрын
  • The approach that makes the code more readable and understandable is the way to go, and it changes according to the context. Once you get your fields, variables, parameters, type names, etc. right, half of the job is done. Having proper naming drives the choice of how to initialize and assign things. Nice video, thanks.

    @RobyMarcellino@RobyMarcellino4 ай бұрын
  • I completely agree with everything you say here. You perfectly summarized my own feelings and thoughts on the topic.

    @josh_flash@josh_flash4 ай бұрын
  • I use var for objects and explicitly define type for the rest; like primary types and string. It makes things less confusing for the developer when working with a returned value from a method call so they don't have to check the type they are working with. Also when refactoring a class name other consumer files won't be effected in the commit. If you change the return type from a class to a bool or visa versa you'll also get a clear error.

    @Benke01@Benke014 ай бұрын
  • IME, I tend to care more about what the content of a variable is than the type. Skimming through a list of declarations of varying types is faster and easier with var, because I am usually looking for " = the result of what code?", not "what type is ?". var puts the start of the information I am looking for consistently in the same column. If I want to know what type is elsewhere in the code and it's not clear from context, I probably just moused over it and read the tooltip as opposed to searching for the declaration line.

    @joshpatton757@joshpatton7574 ай бұрын
  • I didn't used to use var. But more recently I've found myself using it, especially for methods that return ienumerable collections. I was very much of the old camp that I wanted to see what it was. But I mainly read the code in visual studio so I can just hover. And in those situations it's pretty clear it's a collection of objects, and the type of object is normally pretty clear from the method name.

    @robwalker4653@robwalker46534 ай бұрын
  • I always explicitly name my property to the right type in combination with new Ie: Person p1 = new() When generics are involved it depends on the length. I primarily use var in a foreach loop where the context would be obvious like Listnames = GetNames(); foreach(var name in names) Console.WriteLine(name); What do you think?

    @alfflasymphonyx@alfflasymphonyx4 ай бұрын
  • I agree with the first comment you showed. If the type is clear after the equals sign, then the 'var' keyword should be used, which is how I use it. However, if the type isn't clearly defined after the equals sign, then an explicit type should be specified instead. var use = new User(); Response response = new User().CreateUser();

    @taner-saydam@taner-saydam4 ай бұрын
  • If everything is named in a way that makes sense, you're right and it doesn't matter if 'var' or the full type name is used in the declaration. I work with a lot of coding boot camp drop outs who struggle, nay, completey fail to name variables in a meaningful way. Because of this, my team has implemented the rule that the declaration must contain the type, on either side of the statement.

    @SeanWilliams2112@SeanWilliams21124 ай бұрын
  • I think the most important thing is to just be consistent within a project. If you really like var, go for it, if not, don't use it. But for goodness sakes if you get into a project to make a code change, and you see that the code uses var (or doesn't), then stick with how the code was originally written. Don't start mixing the two. If you're using .editorconfig file to control the rule for var usage in your project then even better because it can catch when you're breaking your rule so you can stay consistent.

    @matok2426@matok24264 ай бұрын
  • Still think you should avoid var whenever possible. I much prefer consistency, and half the time when I'm scanning code I'd like to know what to expect before I get to the assignment. Another point I don't see mentioned is if you have similar classes. So your user factory create user, does it return a basicUser premiumUser, or something else? (Bad example but I'm done for the day) Anyway it's your code at the end, and if it works and you're comfortable maintaining it, use var.

    @veec1539@veec15394 ай бұрын
  • I don't mind whatever if I'm part of the team. In my own projects I've noticed that I'm not really consistent in either but I look at readibility mainly. Sometimes I use var when the context is pretty clear (even without explicit type) but I understand and am ok with the rule that the type must be explicitly visible.

    @ekeke7125@ekeke71254 ай бұрын
  • You nailed it when you said that "it has to add value to the code"

    @gabrewer@gabrewer4 ай бұрын
  • Using explicit types is always better, it makes your program more faster and your program's behavior more defined. So if i don't write some javascript or php i definitely want to write with a strongly typed language.

    @haliszekeriyaozkok4851@haliszekeriyaozkok48514 ай бұрын
    • c# is a strongly typed language, and the presence of var doesn't change that fact. the real type is always known ahead of time, since you can't use var if the type cannot be inferred automatically. some IDEs even offer a "type hint" displayed after the var if the type is not apparent to the reader.

      @FakeDomi@FakeDomi4 ай бұрын
  • I use var everywhere, mostly for readability. That allows me to be explicit where i need a base type, for instance, to let my team know that this is a special case.

    @sunefred@sunefred4 ай бұрын
  • I use the Visual Studio option "Show hints for variables with inferred types" which shows the type beside var. It can make your UI a bit more cluttered but I got used to it and find it valuable.

    @cdnkarasu@cdnkarasu4 ай бұрын
    • That seems to be the worst of all worlds.

      @ansgarhellwig6700@ansgarhellwig67004 ай бұрын
    • seems circular... use var but then also show the type...

      @thedreadedgman@thedreadedgman4 ай бұрын
  • The reason I like var for declarations is I read my code in my head in English, and "User user one equals new" (User user1 = new()) is not proper English, so I stop on it every time and reword it in my head so it reads properly to me. "Var(iable) user one equals new User" (var user1 = new User()) reads as English. Also, I haven't read all the comments but I'm not seeing very many people talk about naming variables here. There is almost zero need to have an explicit type on a declaration if you simply name things explicitly. I'm not talking about Hungarian notation or anything like that. I'm talking about the difference between user1 and userJustCreated or whatever gives it full context. Naming is certainly one of the hardest things in programming, but that doesn't mean you shouldn't try to do it right. Name things properly (with context) and the value of the explicit type is diminished if not altogether nullified.

    @sliderhouserules@sliderhouserules4 ай бұрын
  • I know this is kind of silly, but I prefer `var` because the names all line up vertically, and it's easier for me to read.

    @mitchelllienau9303@mitchelllienau93034 ай бұрын
  • I never liked var because I felt that explicit types made it easier for someone supporting my code to understand what kind of variable they were dealing with. I do like the syntax "Customer buyer = new()" because it is obvious that what I am creating is a new Customer.

    @kengunther9211@kengunther92114 ай бұрын
  • Task - good luck with using explicit types

    @nanvlad@nanvlad4 ай бұрын
    • Put a couple of namespace clashes in the front as well 😂

      @kostasgkoutis8534@kostasgkoutis85344 ай бұрын
  • I use the explicit type whenever it is not already explicitly defined elsewhere on the line of code. This is because, after a period of experimentation, we found this to take the shortest time for reading comprehension in our team. During writing I just use var everywhere and then just use the built-in refactoring tools of Visual Studio to convert all vars in the solution to the explicit type where type is not apparent.

    @epiphaner@epiphaner4 ай бұрын
  • The only time I use var is to shorten my typing and use the VS shortcut to turn that to an explicit type. I find var highly confusing: What's the type? Is that an implementation or an interface? Is it nullable or not? Full type is longer but much better for readability. I want to know and have full control on the type of a variable, I'd use weakly-typed languages if I didn't want that. I agree on the use of new(). It needs a bit of time to get used to writing that, but it removes the maybe only reason to use var.

    @kodwhat@kodwhat4 ай бұрын
  • Personally, I like the concise syntax with inlay hints in my editor. This way I don’t need to type out the type manually, but when I’m reading code or doing a code review I can see the type of variables.

    @benheidemann3836@benheidemann38364 ай бұрын
  • Our codebase is a mix of them all to be honest. We are however in the process of fixing this to following a common standard which will be the User user = new(); where ever it is possible. I was very much for the var anywhere when it was first introduced but have later since retracted that opinion to be more of the rule mentioned above instead.

    @CRBarchager@CRBarchager4 ай бұрын
  • I like to have ease to read and write. So agree with calling constructor without type and use explicit type as it makes nested collection or type initialisation nice to read. Var is nice to have alignment and emphasing the data flow and not data types. in VS there is a killer feature with holding alt+F1 to show explicit types temporarily for var keywords Like always then it depends, using var but when initialisation then not using it or when types matters

    @stevenj8261@stevenj82614 ай бұрын
  • As with any kind of debate around code style guidelines, the most important thing is code legibility. Not what is easiest to write, not what looks nicest, but what is easiest to read, particularly for someone unfamiliar with the code base (that person will be you a few months later). With that said, I like the Microsoft suggestion: use `var` when the type of obvious, use an explicit type when it will help with legibility. Of course there is room for debate when it comes to what is obvious and what is legible. I would probably use explicit types in some of the examples you used implicit types. I have spent the last couple of years dealing with a code-base written by an off-shore contract team that did not care about the code they were writing. It works, technically (until it doesn't), but all the naming is lazy and inconsistent, making their code a pain to read and understand. Unfortunately, their internal style guidelines enforced `var` everywhere; having explicit types, even poorly names ones, would go a long way to making their code more readable.

    @entith@entith4 ай бұрын
  • With the ‘[]’ and ‘new ()’ syntax it makes more sense to explicitly type at the front end rather than at the ends of the line.

    @BSDrumming@BSDrumming4 ай бұрын
  • I love the var keyword and agree with your arguments. I prefer better variable naming, cleaner code and having alignment (since all start with var), also relying on the return type and context. Edge case I encountered while refactored some serious legacy code. Changed a whole bunch of methods to return higher level interfaces instead of concrete types. Since "var" wasn't used on the usage side of these methods, I had to go around and change them to var or to the interface. Example: Concrete SomeMethod() {...} Concrete something = SomeMethod(); I changed SomeMethod to return a: IBetterInterface Now Concrete something = SomeMethod(); causes compiler error. While var something = SomeMethod(); would have worked just fine with the new interface. My question, since you didn't show it, is what would you do with basic types? string name = "Nick"; Or var name = "Nick"; Right hand side gives away the type quite clearly. Same goes for: var age = 30; var percentage = 25.77; var success = false; Though i might want explicit types for explicit sizes. For example float vs double. short vs int vs byte etc... I like var for basic types as well if I don't mind the very specific nature and differences of the explicit type (memory size for example).

    @alonmore28@alonmore284 ай бұрын
  • i can agree to use var especially for longer types with generics and so on; i don't use var for primitive types; yes, it's very useful for refactorings, but also it happened to lose context and not really knowing anymore what the type was there, you have to pay attention to that

    @luvincste@luvincste4 ай бұрын
    • I use var all the time, in the declaration row you will know from the assigned value unless its a method return value and in that case its in my opinion better to use var as if I change the return value and all uses of the variable already can handle the new type its less code to change. Also, most of the times I do want to know the type of a variable I just hover over it to get the tool tip, especially if its a big method with many variables where I am more likely to need to check it since the actual declaration is quite often not in view :) And since I almost never use unassigned variables the only real case would be if I assign null and I try to avoid using null as much as possible.

      @davidmartensson273@davidmartensson2734 ай бұрын
    • for me i prefer having some reference points, but sure there should be enough informations/verbosity to not have any problems using var; only, some kind of types are not really refactored, if something is a DateTime it really will just be a DateTIme, so if i can avoid var there then fine; also say int vs var, it's the same length, who cares

      @luvincste@luvincste4 ай бұрын
    • @@luvincste I would want the name of the variable to be such that its obvious its a datetime, like createdUtc or modifiedDate or similar, thats much more helpful especially if you have multiple variable, one for when and one for if so modified is a bool and modifiedDate is when it was modified. And in nether of those cases I can see my self relying on the declaration line since it very very rare that its on the declaration line I need to know the type. And with intelisense and property hints and everything its usually never a problem knowing the type anyway :)

      @davidmartensson273@davidmartensson2734 ай бұрын
    • yeah i know there is essentially all the needed support for using var and abandoning almost all explicit types in one way or the other... still, to me it's kinda annoying seeing vars all around; maybe one day i'll go full var, i don't know

      @luvincste@luvincste4 ай бұрын
  • 7:24 we did a simple poll in our Teams channel for that, interestingly no discussion followed and we just applied the highest voted option (using 'var' everywhere).

    @krccmsitp2884@krccmsitp28844 ай бұрын
  • I type 'var' for simplicity but have Visual Studio set to replace the var with the actual type on save. Best of both.

    @beater6967@beater69674 ай бұрын
    • ngl this is really simple thing but clever as heck

      @mciejgda88@mciejgda884 ай бұрын
  • IMO type hints in your editor and using type inference is just as good, just little inconvenient when you read the code outside of that environment

    @sohn7767@sohn77674 ай бұрын
  • I have 2 thoughts on why to use explicit types: 1, Consistancy if you have to declare the types sometimes, it makes sense to declare them all the time. 2, Auto completion, if you start typeing the type chanses are you won't have to finish typeing the whole thing as intelesence will do it for you, it will also suggest a variable name too based on the type. So chanses are if you want to do "Contract contract = new Contract()" the only bits you are going to actually type are "Con" "=" and "new", while using var you would have to type basically the whole thing.

    @CrashM85@CrashM852 ай бұрын
  • The more experience we have the more frequently we recommend to "just use your brain". The problem is that this "brain" or common sense in development and coding is not really well formed yet for beginner/junior devs. Hence the need to provide more dogmatic code style guides, analyzers, and rulesets. And the sad thing is that for some, this "common sense" never fully develops 😢

    @tafs7@tafs74 ай бұрын
  • I always use var where able. Only times it ever catches me out is when I'm expecting a concrete type, but the method returned an interface. And then I need either some fields or the concrete type itself 10 lines down. Nothing a cast at assignment won't fix though.

    @billy65bob@billy65bob4 ай бұрын
  • Depends, In projects I manage 'var' is allowed as long as the output type is clear by the right hand assignment. If not, explicit types. If a company has rules against using var I also understand especially depending on what kind of static code testing which can't determine the type of var.

    @LagunaCloud@LagunaCloud4 ай бұрын
  • Personal experience: I've never worked in code using var where I couldn't figure out what was going on, even with minimal effort. It shrinks the line horizontally and I'm down with that. I also use the "new way", type on the left and new() shorthand. Just my experiences though.

    @DevLeader@DevLeader4 ай бұрын
  • Are we not going to mention that an advanced IDE like Rider offers you a "hint" of the return type? This is not the actual code but makes it a bit more readable, especially for methods with names that it is not immediately obvious what the return type is. My general take while going is "less code means less maintenance".

    @OmriYaHoo@OmriYaHoo4 ай бұрын
  • We do? I didn't know 😅

    @buddy.abc123@buddy.abc1234 ай бұрын
  • I use `var` everywhere. The most important is the names of variables and methods. Of course, I prefer "target-type new expression" feature of C#9 when possible.

    @AlexBroitman@AlexBroitman4 ай бұрын
  • var was a problem when it was introduced, and will always remain so. It's a feature that flies in the face of a statically type-safe language. We like it because it means we type less. It's a convenience, born out of a certain level of laziness. But the use cases were var can make code more readable will always be less, and lesser, than those were it can make it hard to understand, especially when reading through it. Which makes the use of var very hard to do consistently in a project of any size. Instead, var is more useful in those contexts where type safety is dynamic and thus evaluated at runtime. And it is telling that the newer type shortcut tremendously reduce the use of var and programmers actually prefer them to var.

    @Marfig@Marfig4 ай бұрын
  • var makes a lot of sense with generics. I prefer var everywhere , cause I trust the compiler. 2 reasons not to use var: If return type inference must be explicit: IUser vs User (but that's a leaky abstraction anyway) And The newer syntax when I need to specify more parameters, like a complex data object

    @biohaz999@biohaz9994 ай бұрын
    • I'd also add initialization outside of first assignment Person p = null; if (condition) { p = GetPerson(); }

      @NickMaovich@NickMaovich4 ай бұрын
    • You can trust the compiler. As C# is type-safe the compiler keeps track on the type infered. The 'var' is for humans

      @mortenthomas3881@mortenthomas38814 ай бұрын
    • @@NickMaovich Person? person = null; ;)

      @biohaz999@biohaz9994 ай бұрын
    • You trust the compiler but I don't trust humans and neither should anyone for that matter. People reading code should be certain of what they are reading and people writing code should write it so others can be certain.

      @TizzyT455@TizzyT4554 ай бұрын
    • @@TizzyT455 This. Why do we even _have_ high-level languages like C# in the first place? To improve productivity of and comprehension by humans. Coding standards exist to reinforce that, and should be designed accordingly. To an extent, productivity and comprehension are in tension: do you want to do less typing, or to spend less time understanding what someone else has written? To me, that's a no-brainer: software typically spends 90% of its lifecycle in the “maintenance” phase, so I prefer being as explicit as possible, as often as possible. (That said, I’m a “team player”, so when I work for a group that votes for a different standard, I follow that standard instead of being a prima donna about it.)

      @sleeper-cassie@sleeper-cassie4 ай бұрын
  • I prefer explicit types just because when working with a team something that is obvious for you might not be for someone else or even if it is they still need to check it which takes more time that just writing explicit types in the first place. With something like var value = 14.5; the intent might have been to use float, but the one who wrote it forgot to add 'f' in the end and now it's double.

    @Kossura@Kossura4 ай бұрын
    • Explic types are easier for code review in DevOps where you can't just hover over the keyword to see if the correct type has been used. I only ever use var for Linq queries.

      @nathanfreeman-smith6817@nathanfreeman-smith68174 ай бұрын
  • I use var for everything, except builtin types (int, string, double, byte). So my type specifier is always colored as a keyword. These names are already short and usually are important, like you need to be aware is it int or uint or long or double. In all cases for classes a good variable name is much more important, because the declaration is on a single line, but usages may occur multiple times far enough from the declaration.

    @izobrr@izobrr4 ай бұрын
  • I don't remember where I saw it (couldn't find it again if I wanted to) but I read some article where this guy had a rare bug where the IDE thought var was type X, but ultimately when compiled ran it was type Y and was runtime into hard to debug runtime exceptions. Chances you'll never see the same bug, but it is always a possibility depending on how abstract your code becomes. This could be a pro or con depending on how you like to do things, but also with var, you can change the return type on a method and any caller now magically has the new type. Personally if I'm making the conscious decision that a method should return a different type (maybe I'm splitting a class apart or refactoring) I'd rather get a compile error because I am not using var anywhere versus having it seem fine at compile time because it's using var but results into a runtime error because I missed a spot that calls said method. I do like the newer one where you have the explicit type on the left and only a new() on the right, along with initializers and what not. As to whoever the OP was that Nick was responding to where Rider suggests using var everywhere - that's just a bad dev setup. Whatever team he's working on should have a project level configuration that changes the Rider suggestion of use var everywhere to use explicit + new() everywhere. I know this is configurable.

    @kiwiproductions4510@kiwiproductions45104 ай бұрын
  • The shape of code is information to me, so I greatly appreciate var and prefer it over shorthand-new

    @Bliss467@Bliss4674 ай бұрын
  • My mindset is-- if using "var" leads to being unclear as to what type of variable you're working with, the var keyword is not the problem. 100% you have some poorly named method, and you should reconsider that way before you consider not using var. The only time I would use explicit types is when you're upcasting something, like Animal defaultAnimal = new Dog();

    @andrewshirley9240@andrewshirley92404 ай бұрын
  • I really like the clean way when we "var" brings us. I prefer to invest in naming conventions than to explicit the value type.

    @elitonluiz1989@elitonluiz19894 ай бұрын
  • I use var everywhere unless I explicitly can't because the compiler tells me it can't figure it out on its own. This only happens with Actions and Funcs but that's really the only time that I don't use var. I like to declare any variables as far up in a method as I can so I can group them together as much as possible and it's so much easier for me to follow each variable when they are all left aligned on the same column which I wouldn't be able to do with explicit types. As for using the new() shorthand, I don't like using it because my eyes tend to look at the right side of a statement to see the type whether it's a new object or a method call. I can see the benefit of it's use, but I'd much rather explicitly new up the type rather than use the shorthand, even for class members and fields. I value well named methods and variables over explicitly declared types any day.

    @stevenodlum4563@stevenodlum45634 ай бұрын
  • The most important thing is that it roots out the toxic code calling a large meeting to discuss it so you know who to avoid...

    @LeifErshag@LeifErshag4 ай бұрын
  • Nowadays it can easily be set via .editorconfig, and at least Visual Studio (I guess Resharper/Raider too) will automatically switch between var or explicit type. I like using var everywhere, because I never care about what the return type is. If it can be passed somewhere, or used later, it's ok and it will be pretty apparent from the context. If it can't then it won't compile anyway. C# is a type safe language, so I leave the compiler to enforce type compatibility. So I set my .editorconfig to enfore var, and now whatever I write, it will be refactored to var when I hit save. But if I were to work in a team that preferred the other way - it'd be equally fine. Just set .editorconfig right and it'll be autocorrected.

    @DemoBytom@DemoBytom4 ай бұрын
    • That's a great point, you can let your IDE show you the actual type as well as method parameter names etc, just hold down CTRL in Rider. Meanwhile people who prefer var and can read context better can't make the types disappear, the world is not fair! :)

      @the-niker@the-niker4 ай бұрын
  • Ah, finally! An episode where I understand everything that you said from start to finish. Hahaha!

    @christoperpineda9181@christoperpineda91814 ай бұрын
  • It's not just about being able to easily read the existing code block. Do I want to see a compile error when the calling method is refactored and the return type changes or should the changed type be converted automatically? The answer to this question is not that simple. Sometimes seeing a compile error may lead to more conscious coding, but it can also slow down the coding considerably. In some examples; there are so many nested generic types that their names are too long or the name of a single DTO is too long, this is where it becomes very useful. It may not be preferred for polymorphic instantiations. More than these, creating that variable in every line and not leaving work to the garbage collector will reduce this conflict. I like single line builder patterns more. At the end of the day, all of them is trade off. I think it should not be concluded that "it should definitely be like this".

    @Imploser@Imploser4 ай бұрын
  • the only "Mistake" in all of this is having the IDE say that "not using var is a syntax WARNING" like TF, reserve that for an ambiguous conversion and stop telling me when var is valid.

    @gardian06_85@gardian06_854 ай бұрын
  • I use `var` everywhere. IDEs can show the type next to it in smaller font, or I can hover and get a tooltip, and as an added benefit I don’t need to keep track of it and fix all callers of a function for a minor type change.

    @Kwpolska@Kwpolska4 ай бұрын
  • I've used both var and explicit types. But I kind of like the newer syntax to instantiate objects; EplicitType explicitType = new(); The only issue with the new syntax is when I'm writing newer code and then have to go back to legacy code where it's not an available feature or won't compile.

    @iSoldat@iSoldat4 ай бұрын
  • i despise var bc when i have to look at function names to infer the type, it just takes 3x longer than just seeing the type immediatelly. ive experimented a bit with var tho, like with tuples. bit i think that every time i use it, its a sign that i have messed somewhere up, and should probably refactor. its like goto to me

    @wuketuke6601@wuketuke66014 ай бұрын
  • Mostly using `var` everywhere, the only benefit from not using `var` I can see is that code review outside VS might be easier. But given now I mostly for with F# and it has on `let`, no other option :-)

    @GlibVideo@GlibVideo4 ай бұрын
    • Yes, imagine F# devs discussing whether they have to always specify types =)

      @VoroninPavel@VoroninPavel4 ай бұрын
  • var has been made obsolete with the new initialization syntax ( "new()" for object and "[]" for enumerables). Personally i prefer the new syntax so i always have the type on the left instead of a indeterminate point at the right. also i don't like it when used when the type on the right is not immediately clear. It's perfect use is as a temporary result placeholder to be refactored to the concrete type AFTER you have finished the code . Readability, clarity and consistence should be the main priority after code correct execution

    @albe8479@albe84794 ай бұрын
    • "var has been made obsolete with the new initialization syntax" you would think... Sadly, no. But I hope your sentence will be true very soon. :)

      @ozsvartkaroly@ozsvartkaroly4 ай бұрын
    • @@ozsvartkaroly for new code maybe. for old code,probably not worth the time

      @albe8479@albe84794 ай бұрын
    • @@albe8479 Sure!

      @ozsvartkaroly@ozsvartkaroly4 ай бұрын
  • I like var when I know I have to create a variable of some type, but have not fully clarified at the moment what exact type is, and have to decide later For example I know I want a collection, but at the start I'm not 100% sure, whether it has to be list/array, or simple ienumerable is fine. So I start var x = coll.Select(...), then maybe slap a ToList() at the end if I need extended functionality, or leave as is.

    @klocugh12@klocugh124 ай бұрын
KZhead