"Don't Use Fields in C#! Use Properties Instead" | Code Cop

2023 ж. 8 Қаз.
93 624 Рет қаралды

Use code TDD20 and get 20% off the brand new Test-Driven Development course on Dometrain: dometrain.com/course/from-zer...
Become a Patreon and get special perks: / nickchapsas
Hello everybody, I'm Nick, and in this episode of Code Cop we'll take a look at some really insane advice that says that you shouldn't use fields in your C# classes, but instead private properties.
Workshops: bit.ly/nickworkshops
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasGitHub
Follow me on Twitter: bit.ly/ChapsasTwitter
Connect on LinkedIn: bit.ly/ChapsasLinkedIn
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер
  • At this point I feel like people post bs on social media just for the interactions, positive or not. They didn't intend to educate, they intended to cause controversy.

    @Ba_Dashi@Ba_Dashi7 ай бұрын
    • It's a point of view, but I believe that these people go around putting up these absurdities to get the title of MVP.

      @ddrsdiego@ddrsdiego7 ай бұрын
    • Well its their job getting paid off view so they gotta bait the clicks 😂 i hate tech influencers

      @BlackDub21@BlackDub217 ай бұрын
    • can it be an advice from chatgpt?

      @verzivull@verzivull7 ай бұрын
    • its called rage bait posting.

      @envo2199@envo21997 ай бұрын
  • Rule #1: Never take advice from someone who calls fields "class member variables".

    @amirhosseinahmadi3706@amirhosseinahmadi37067 ай бұрын
    • Good one 🤣

      @Z3rgatul@Z3rgatul7 ай бұрын
    • I remember a series of otherwise decent C# tutorials on KZhead that insisted on calling fields "attributes". Yeah, that's totally not going to get confusing later...

      @EdKolis@EdKolis6 ай бұрын
    • 😂😂

      @user-ji2yk7wu4n@user-ji2yk7wu4n6 ай бұрын
    • "class" + "member variables" I would consider to be redundant (it's like saying "general consensus"), but I don't have a problem with "member variables" or "fields" to mean the same thing. Indeed, "member variables" balances nicely with "local variables".

      @MrMatthewLayton@MrMatthewLayton4 ай бұрын
  • This is one of those what I call "level zero" instances. Where someone doesn't even know that they don't know. It's very dangerous, especially if others use the advice from such ignorance.

    @scottpageusmc@scottpageusmc7 ай бұрын
    • So true. For example, this person doesn't know he can just update editor config to eliminate underscores. Would rather build an anti pattern. Lol

      @7th_CAV_Trooper@7th_CAV_Trooper7 ай бұрын
    • i actually like the class field nomenclature for exactly the same reason nick explains. i still use the m_ notation though xD

      @christophbornhardt7888@christophbornhardt78887 ай бұрын
    • @@christophbornhardt7888I prefer 'this.privateFIeld', and I set stylecop up to complain if any fields do not have a 'this' prefix. However each to their own, they achieve the same thing. I also used to use m_, but 15 years ago.

      @vonn9737@vonn97377 ай бұрын
    • And if ChatGPT picks this up as "good advice"...hehe

      @DaneWithADrone@DaneWithADrone7 ай бұрын
    • the person who uses it is a staff engineer in my company. What should I do? any advice

      @minhhieugma@minhhieugma7 ай бұрын
  • I have a feeling that they read a textbook reasoning for using public properties vs public fields and confused it with the reasoning for property vs field in general.

    @samsim4648@samsim46487 ай бұрын
    • they will have a better position to protect their idea if it is a public one. But here in this context, we are talking about the private scope. Imagining when you have to talk to your "higher position" about this. I feel hopeless

      @minhhieugma@minhhieugma7 ай бұрын
    • That's exactly what I thought. Some of the listed advantages only make sense when you're thinking about choosing public properties over public fields (which is a good idea). Mocking for example.

      @justindoyle8091@justindoyle80917 ай бұрын
    • Noob question, but when is it appropriate to use a public field? I find myself only using public properties or private fields, I don't know when I should be using a public field

      @slowjocrow6451@slowjocrow64517 ай бұрын
    • @slowjocrow6451 For data struct members, one often doesn't want even the minuscule indirection of a property when doing high performance data processing.

      @RiversJ@RiversJ7 ай бұрын
    • @@slowjocrow6451idiomatic c# doesn’t use public fields, only public properties. Edit: riversj makes a good point,but depending on your domain you might never be in that niche scenario

      @slimbofat@slimbofat7 ай бұрын
  • Rider & R# have options to provide extra colourisation based on semantics, which means you can define a different colour for a field so don't need to use an _ to make that visible. It also lets you immediately tell the difference between a parameter, a local var that's only assigned once or a more frequently mutated local var; or a normal class, a static class or a record etc, and similarly for static vs normal methods etc.

    @GufNZ@GufNZ7 ай бұрын
    • Yeah but I dont think one should rely on everyone who will ever read this code to have such an IDE and setup

      @neralem@neralem7 ай бұрын
    • You should *always* use an underscore prefix for intellisense. At a lower level, it's the standard way for expressing intent.

      @joshuawillis7874@joshuawillis78747 ай бұрын
  • We (Eight Sleep) have a "zero clutter" rule, we don't use _ or even "private": never had a readability issue because if something is came-case it's either from your current method or a private class field.

    @massimoandreasibassi7016@massimoandreasibassi70167 ай бұрын
  • I hate underscores. I use this to access class private members. Thanks Nick for agreeing with me. 😄

    @dr_Bats@dr_Bats7 ай бұрын
  • I am using private readonly fields without underscore - 100% agree with Nick 🙂

    @joergw@joergw7 ай бұрын
  • Hot take - underscore fields are a remnant of c++ devs coming to C# originally. Mandatory "this." on everything is much more readable and gives clear distinction between local and class variables and methods (passing lambdas as paramaters, anyone?). A method should not care if a class-level variable is public or private, that is for the class to decide and change as needed, not a method. I do use underscores in my code, but only as a warning for any field that must never be accessed without a getter/setter. I agree private property makes little sense but if you feel that way it should give you a pause to consider if the property shouldn't be protected instead, especially in library code.

    @the-niker@the-niker7 ай бұрын
    • I agree that underscores should be used to denote private backing fields that should not be accessed directly (ie backing fields for source generated change notifiyng properties, that would not work otherwise). To specify that what we're accessing is a class member rather than a local variable, we can still use the 'this.' which is more explicit

      @CristianBaldi@CristianBaldi7 ай бұрын
  • I actually recall seeing this in a Fowler / Martin book on clean code. It escapes me why they recommended using a private getter, but I think the reasoning was improved readability in the "NameYourVariablesSomethingVeryDescriptive" category, and that they claimed that IDEs are so powerful now you don't need the underscore to tell you it's a private variable. Either way, this certainly isn't a hill I'd want to die on and it boils down to developer choice.

    @qtxsystems@qtxsystems7 ай бұрын
    • I think this is the answer. I had this conversation more or less a month ago with friends from work. I don't see a need for the underscore but I don't dislike it either. It's visual preference.

      @EldenFiend@EldenFiend7 ай бұрын
    • How does that improve readability at all? I dont get it...

      @CZProtton@CZProtton7 ай бұрын
    • ​@@CZProtton Because then you start with an auto property, single line of code? Only expanding it if and when you need more than just a property with a hidden backing variable

      @MostlyPennyCat@MostlyPennyCat7 ай бұрын
    • Without an underscore, a camelCase variable will resemble an argument. To differentiate them, you should add "this." on the field. But adding "this." is not enforced by the compiler, but the underscore is (of course, since it's part of the variable name). Ergo, the underscore is better for private fields.

      @jeffmccloud905@jeffmccloud9057 ай бұрын
    • IDEs are powerful now for sure, but we often read code not in IDE, e.g. in a web interface during PR review. Or maybe you want to access some private fields, start typing with _ and LSP will show you the list of them so you don't need to remember the exact name. This makes life a bit easier. But m_* convention is ugly though :)

      @vd3598@vd35987 ай бұрын
  • I think for the validation aspect they meant in an init block, which is nicer than cluttering up the constructor in my opinion. Though we'll need a different solution for primary constructors on classes I don't think you've understood how they and we implement lazy loading, it would be with a Lazy field as you say but then an expression bodied property returning the .value. we have used this before though sometimes there is a better overall design.

    @MarkAdamson-Eddie@MarkAdamson-Eddie7 ай бұрын
  • The 9 points just look like something ChatGPT would generate.

    @jamesroot9777@jamesroot97777 ай бұрын
    • From my experience with ChatGPT, it would be smarter than those stupid ideas and arguments against fields.

      @AlFasGD@AlFasGD7 ай бұрын
    • @@AlFasGD I agree, but I think they asked it to generate an article arguing FOR it..cus it will do that haha

      @ferd1775@ferd17757 ай бұрын
    • ​@@AlFasGDit is smart, when you're smart. Sometimes you can make it write something stupid, sometimes it does so by itself, and you need to be smart enough to discard it.

      @baetz2@baetz27 ай бұрын
    • More and more, they might actually be so.

      @benjamininkorea7016@benjamininkorea70167 ай бұрын
  • At least one of the reasons given by the author of the post is correct. 7. In the case of a property, it is easier to debug what code changes the value of this property. But you're right that the rest of the reasons make no sense.

    @Integer0@Integer07 ай бұрын
  • Sometimes I temporarily change private fields to private auto properties so I can put a breakpoint in the setter. But I prefer private members to be fields too.

    @neralem@neralem7 ай бұрын
    • I got fooled by your avatar! I really thought I had a fly on my screen.🤣🤣🤣

      @alfflasymphonyx@alfflasymphonyx7 ай бұрын
    • @@alfflasymphonyx Me too. You got me.

      @sealsharp@sealsharp7 ай бұрын
  • So glad to see you'll be speaking at Techorama Netherlands. I'm looking forward to attend your talk. See you at Techorama. Love the content. Keep it up.

    @raldotromp@raldotromp7 ай бұрын
  • With debugging I think they met that if you have `set;` or `get;` then you can create a breakpoint exactly on those things. You do not need to declare body. This way you can put breakpoint when data is modified/accessed.

    @mrShot94@mrShot947 ай бұрын
    • That's what break on value change can already do. It just shows the person has no clue how to use a debugger

      @LeutnantJoker@LeutnantJoker7 ай бұрын
    • In my opinion, if you are performing complex logic when getting or setting a field, then that should be the job of a well named helper method or extension method. Because in the calling code, merely “getting” a value doesn’t necessarily tell the reader what is happening to that value before it is being delivered to the caller. So if you had a variable called appleNames and your getter logic returns the list as an alphabetical list, then you should have created a private method called GetAppleNamesAscending() paired with a field. That way your code doesn’t look like it is doing magic. Every time you have magic, it takes a few seconds, up to a few hours, to understand what’s going on. Multiply that by hundreds of these little magical code references and you’ll have a mess on your hands.

      @joshman1019@joshman10196 ай бұрын
  • We switched our codebase to this approach as soon as get-only properties released. I agree that the original author reasoning is dogsheesh. We switched mostly for constructor arguments: 1. they have a tendency to change from private to say public, just change mod 2. improved readability 3. no need for readonly, sometimes devs forget it 4. you see pascal-case you know it came from constructor. 5. having accessor method does not affect performance 6. R# helps create property from argument, code coloring also helps 7. code style consistency, public properties, private properties (injected, state from outside), fields (impl details)

    @BearJewOo@BearJewOo7 ай бұрын
    • Purely feedback on your points to play the other side of the debate. 1. A (if not the) major reason devs expand accessibility is because they find their code is coupled and they want to break the Law of Demeter instead of following best practices. 2. This can't be more subjective. "The Industry" vastly agrees that _thisStyle is more understandable for what it represents. 3. Sometimes devs forget to remove the "set;". Also, "readonly" explicitly says what is happening. A property with only a getter has to be understood. Though as of C#9, you can use "get; init;" which also becomes more explicit. This doesn't change the rest of the points though. 4. Same as #2. We would certainly hope we know PascalCase means it is a class member and not within the function scope. But most of the industry would see PascalCase as a property that might change state. 5. An empty accessor method may not measurably affect performance, but the assertion with some of the "benefits" of the OP is that the accessor method would be abused. 6. I cringe whenever somebody changes their Software Engineering principles to suit a random tool. 7. Nobody can argue with Company Standards. They're up to you and your architects. But this would not match "code style consistency" with the rest of the industry. As for { get; init; } (Which is not part of this OP), that is mainly for records; AKA Structs, Models, DTO's, POCOs. This video and all of the replies so far are talking about interfaces as class members. So those are talking about Services, not Models, and it is irrelevant.

      @JinnFletch@JinnFletch7 ай бұрын
    • ​@@JinnFletch You are absolutely right, both semantically and technically. But I was not talking about "your fancy nanoservice SOLID YAGNI KISS etc code", I was talking about "everyone else's gigaservice WTF LOL WUT code". And in large classes readability matters. As well as debugging. Like you can put a breakpoint on a setter, find all references of a setter or getter. I personally dislike that underscore-snake-camel naming, still I use it to be consistent with the rest of industry which uses it for private members only, no one exposes this naming. So why be consistent? And of course there is just no such thing as "The industry". I'd rather call it crab bucket.

      @BearJewOo@BearJewOo7 ай бұрын
  • I can't say that the underscores are a bad thing. It's less "pretty" but it's useful to know at a glance when I'm accessing a private variable. And I like adhering to standards for when other developers need to see my code so they are more likely to know what's happening at a glance too.

    @VeggehGaming@VeggehGaming7 ай бұрын
    • I like underscores in private field names. It highlights them as what they are, and I immediately know how to handle them.

      @brianviktor8212@brianviktor82127 ай бұрын
    • I always interpreted it as supposed to be ugly so that you ignore it when skimming the code. As you usually look for properties or public members when skimming code.

      @dantecavallin8229@dantecavallin82297 ай бұрын
    • @@dantecavallin8229 this is exactly how it was designed in python, where everything is public, underscore just suggest not to use it

      @qj0n@qj0n7 ай бұрын
    • @@dantecavallin8229 True. They look different and like something you wouldn't want to expose to others (consumers of your library). And I like marking them as such... or "uglify" them.

      @brianviktor8212@brianviktor82127 ай бұрын
    • @@brianviktor8212 I do the underscore only for backing fields if I need them for a property.

      @MrOudoum@MrOudoum7 ай бұрын
  • This could be somewhat defensible if it means to only access fields within properties, in case you need to add lazy loading or something later. But it's hard to justify a sweeping change only to simplify a refactoring that is already simple, and that may never happen. The point about mocking may be that you can make properties virtual and override the return values for testing. This works, but the simpler advice would be to let them be injected.

    @TazG2000@TazG20007 ай бұрын
  • I'm one of those people who was trained with the default StyleCop rules ages ago which enforced that you prefix fields with "this.". To be honest, I was a monster who did that in C++ as well because I thought it was clearer (well, "this->" in that case.). I'm finally warming up to the underscore prefix.

    @vargonian@vargonian7 ай бұрын
    • Same here. Everything that belongs to the class starts with this. If it starts with a lower case, it's a field. If it starts with an upper case it's a property. If it ends with ( then, it's a method. If the call doesn't start with this, then it's static. The fact that this advice starts with saying that it's nice to have no underscores shows this writer could not think outside a convention and may not even know about the StyleCop way.

      @OnnoInvernizzi@OnnoInvernizzi5 ай бұрын
  • "bullshit" - perfectly delivered feedback. CLEARLY this person has no idea what a property and field do at the lower-level. It's not JUST syntax sugar; it transposes the accessors at the lowered-level; and properties re-invoke every time they're called just like a method, so it's just more and more potential allocation; far more than a field FOR SURE.

    @asteinerd@asteinerd7 ай бұрын
    • Not sure. For auto properties an optimization should work which uses the field directly without get/set method

      @isnotnull@isnotnull7 ай бұрын
  • Once I worked in a project that was using camel case for fields and was enforcing "this." and although I initially thought it is weird then in the end I think it is very expressive. In the end, it doesn't matter much, you just need common convention within the team and that's it - whatever you agree on is fine. About the main topic: it's probably not even worth commenting... but it's a bit surprising that AI can come up with such gibberish while having entire SO as its source.

    @proosee@proosee7 ай бұрын
  • I'd bet my bottom dollar that someone asked chatgpt(Edit: chargpt to chatgpt; typo) to write an article SUPPORTING this, and they published that crap 😂😂😂

    @ferd1775@ferd17757 ай бұрын
    • I bet they use the 9 reasons from chat gpt

      @peanutcelery@peanutcelery7 ай бұрын
    • It actually sounds like ChatGPT. No way a human unironically wrote "9. Mocking and Testing: Simplify testing and mocking." as an argument for properties

      @benedani9580@benedani95807 ай бұрын
    • f... each comment makes it sound more and more like chatgpt

      @christophbornhardt7888@christophbornhardt78887 ай бұрын
    • But don't worry, they're going to write a followup article about how bad chatgpt because of the feedback it's recieved....which is also biased and bullshit hahahah

      @ferd1775@ferd17757 ай бұрын
  • Nick, properties ain't always about encapsulation, but, in general, about adding a level of indirection, another layer of abstraction. From this perspective private properties are absolutely fine.

    @denissmith8282@denissmith82822 ай бұрын
  • In my opinion Getters shouldn't compute anything, small transforms are ok, but anything with even minor performance impact should go to the method. At least I'll know to cache the value if It's used more than once and I wouldn't do that with a property

    @PPSzB@PPSzB7 ай бұрын
  • Some of these posts are the computer equivalent of wives' tales

    @mariocamspam72@mariocamspam727 ай бұрын
  • It's just new devs who don't understand what a field is for, and heard that auto-properties was a good feature to come to C#.

    @1992jamo@1992jamo7 ай бұрын
    • I'm a new developer and i know differences between both and when use

      @zoiobnu@zoiobnu7 ай бұрын
    • i assume hes talking about a majority. i take a lot of interns that dont have any idea of this concept

      @christophbornhardt7888@christophbornhardt78887 ай бұрын
    • @@twitchizle which feature?? the properties vs fields???

      @christophbornhardt7888@christophbornhardt78887 ай бұрын
    • @@twitchizle Sure, are you asking when to use fields vs properties?

      @1992jamo@1992jamo7 ай бұрын
    • @@christophbornhardt7888 Exactly right mate. I see it all the time.

      @1992jamo@1992jamo7 ай бұрын
  • While I don't agree with all the hilarious benefits that tip creator was claiming. I still prefer private properties for a number of reasons. 1. Why not? you're making this sound like some new outlandish idea - guessing this is just for the views? 2. Nothing wrong with future proofing in case you do need to add some logic to the getter later if required. 3. IDE's love properties. "Oh no, what's setting my private field, sure wish I could just put a breakpoint in it like I can with a property". "Gee whiz, it sure would be nice to tell at a glance if there are any usages of my private field in this class and what they are like I can with properties". You're completely throwing out the whole dx because you view it as more correct to have a private field? Come on man, there's no "actual" downside but there are arguably a couple gains. The original image is definitely way off base on the why, but I'll personally still continue using private properties.

    @JohnWII@JohnWII7 ай бұрын
  • I believe they take the ideas from "are-there-any-reasons-to-use-private-properties-in-c" Last week, when I asked my staff engineer why he declared a private property to inject a service into a class, he gave me the above link - It is a private field/property and you have full control on it. Why do you need to make it as a property for some chance that likely never exist? - And if your logic is consistent, you should always use string/array to represent any values and should not use integer, float, double, decimal, object etc since you may need to change the type in the future.

    @minhhieugma@minhhieugma7 ай бұрын
  • Code Cop is awesome. I don't even think the underscore is not pretty. As you point out, when you're deep into a class you know exactly what that variable is; without the need to scroll to the top. But if you have public and private auto-props, there's no way to know by the standard naming convention. I choose to believe the person who made that original post made it for rage bait.

    @Ayymoss@Ayymoss7 ай бұрын
  • This is like applying all the reasons for public properties instead of member fields to private member fields. Trying to encapsulate private data is misunderstanding the whole concept of encapsulation on a fundamental level. And yes, there is nothing stopping anyone from naming their private fields the same way as public properties. The language doesn't limit your coding standards, but they do exist for a reason.

    @SG_01@SG_017 ай бұрын
  • In my first job, as a junior .NET developer. I remember the "solution architect" of the application I were working on told the team we had to always use properties instead of fields, like in this video. I questioned him on why, but he had no answer for why. Shows there is a lot of bad advice being pushed by people that don't properly understand what they are advising.

    @eradubbo@eradubbo7 ай бұрын
    • it is really hard to debate with a higher position especially if they give you a StackOverflow link of a highly rank author: are-there-any-reasons-to-use-private-properties-in-c

      @minhhieugma@minhhieugma7 ай бұрын
  • Thanks. Commented on this LinkedIn post

    @DlinnyLag@DlinnyLag7 ай бұрын
  • I really think you should make a video and go into detail about fields vs properties, when to use one vs the other, why, etc

    @fxandrei@fxandrei6 ай бұрын
  • Definitely fields is my choice. And that underscore helps me to know i'm using a private field later in code.

    @MilanDendis@MilanDendis7 ай бұрын
  • I prefer the StyleCop way of using "this". That way you can easily see that it's a class field. Also, you can also easily tell the difference between methods calls to static methods and non-stick methods because the StyleCop analyser informs you to prefix "this" on calls to non-static members.

    @sajilicious@sajilicious7 ай бұрын
    • this is it.

      @sealsharp@sealsharp7 ай бұрын
  • I totally agree with you Nick. I just have an issue with the underscore which i dont prefer. I tend to use "this." in the constructor for e.g. DI

    @DaneWithADrone@DaneWithADrone7 ай бұрын
  • I know the use case for that 1) Create a class OuterClass with a private _field 2) Declare a private class inside with some method 3) Inside this method create an instance of OuterClass, e.g. var outerInstance = new OuterClass() 4) Boom! outerInstance._field is available. P.S. Sometimes I use this approach for xUnit tests with [ClassData] attribute, where all initialization of services is in outer class and all testcases described in the private inner classes where they have access to inner state of a parent class

    @nanvlad@nanvlad7 ай бұрын
    • Hi! I dont't know what you meant, but what I "understood" from this was something like this: class OuterClass { private int _field; private void SomeMethod() { private class InnerClass { private int _innerfield; } var outerInstance = new OuterClass(); } } and this doesn't make any sense. Could you please provide us some example code? As it sounds interesting.

      @g3ff01@g3ff017 ай бұрын
    • @@g3ff01 Hi, here is a code sample. If you try this approach for testing with xUnit and ClassData, you'll see a different visualization in VS TestExplorer public class Outer { private int _outerField; private class Inner { public int GetOuterField(Outer outer) => outer._outerField; } }

      @nanvlad@nanvlad7 ай бұрын
    • @@nanvlad thank you

      @g3ff01@g3ff017 ай бұрын
    • You are violating clean code rules already by declaring a class inside another class.

      @heiko3169@heiko31694 ай бұрын
  • "It should be readonly" Love it and I can't help protecting fields as much as possible.

    @kzryzstof@kzryzstof7 ай бұрын
  • Related question. I have a public read-only property (only has a getter) backed by an explicit private member field. I do this so I can use the field explicitly within the class, to avoid the (slight) performance hit from calling the getter method that gets generated for the property. The compiler could very well be optimizing the code by inlining that call anyway, I don't know, I haven't bothered to check. But my IDE is recommending that I use an auto-property instead of an explicit backing field. This is a computation-intensive application that does need to be concerned about performance, so would an auto-property be optimized away during compilation (either IL compilation or JIT compilation), so I can go ahead and use one? Or should I continue using my explicit backing field?

    @davidfrogley7117@davidfrogley71177 ай бұрын
  • Good shot, Nick!

    @pavelromashuk237@pavelromashuk2377 ай бұрын
  • I love this series! I take a drink every time I guess what you are going to say!

    @stevestrong9363@stevestrong93637 ай бұрын
  • because I'm an autocrat sure.. but here is my answer. Code should be self documenting, Fullstop. Herewith the same and some good advice. I prefer the concept of having "all" interfaces implement either ITransientDependency, IScopedDependency or ISingletonDependency interfaces. These "By Convention" interfaces does not implement any code however they have beautiful purpose. Other than auto registration, when looking at a class I can clearly see what lifetime scope I'm working with without browsing to some arbitrary improperly named builder extension class. Another example of self documenting code supplementary to understanding why an underscore should exist for fields. People are lazy and don't respect their code, reminds me of people camping in a beautful forest and leaving their trash behind. Yes the camp was a success, but not for the next person wanting to enjoy it. Here is the golden rule of code..... "You don't own the code you write", so look after it and stop being lazy. Few understand this

    @I69420H@I69420H7 ай бұрын
  • @5:40 For a time, MS C# naming recommended to not include the underscore and to just start with a lowercase character. I think around the time dotnet got the native decency injection is around when it was changed to use the underscores.

    @computer9764@computer97647 ай бұрын
    • Thank you for commenting this. A long time ago I switched from prefixing with underscore and using camel case solely because it was in the C# style guide at the time. I'm glad to see this has changed because it makes it so much easier to differentiate fields vs parameters and variables in methods without bloating the code with this statements everywhere

      @matthewrobertson6249@matthewrobertson62497 ай бұрын
    • I thought the modern standard was to not include the underscore since a lot of Microsoft's documentation uses this standard. I guess I was wrong :(

      @jsxpt@jsxpt7 ай бұрын
  • I use private properties instead of fields because the IDE tells me if, and where, it's being used automatically. I'm not sure why it can't do that for fields too. I also use Pascal case for class variables and camel care for method variables to distinguish. I only use the underscore for backing fields of properties so the caller knows not to use them.

    @MRJerrod410@MRJerrod4106 ай бұрын
  • Underscores in fields are just a naming convention(code style) which can easily be changed (I wonder how amazed the person will be when they encounter editorconfig). I guess what happens with a lot of people these days is that they have no understanding of how the `IL` works on the background. They would think that what they see is what the computer actually runs. Thanks for the Video

    @nickpolyderopoulos3491@nickpolyderopoulos34917 ай бұрын
  • Hello Nick, great lesson to me, and I wonder how do you auto fix the sting to string at 5:58?

    @user-mo8fo6bs1q@user-mo8fo6bs1q7 ай бұрын
  • 8:30 What I think he means by "versioning" is that you can keep the properly around as a fancy getter/setter if you 'deprecate' it in a future revision of your API. So that code that expects it still works and doesn't blow up. But that's a moot point, because it's not the API's job to provide compatibility with its internals.

    @billy65bob@billy65bob7 ай бұрын
  • Maybe, with versioning, they were referring to binary compatibility. Where, if in one version you first have a public field, but in a later version you change the field to a public property, you would introduce a breaking change on a binary level. Whereas, if you work with a public property from the start, you are free to change the underlying logic without introducing a breaking binary change.

    @insa07@insa077 ай бұрын
    • The case that we don't have any 'public' members - they all private

      @nanvlad@nanvlad7 ай бұрын
    • That's exactly what they refer to, and given the knowledge the person has about the language, they would still fail to understand what they are proposing for.

      @AlFasGD@AlFasGD7 ай бұрын
    • There's no way they're referring to binary compability considering the rest of the post.

      @Stealthy5am@Stealthy5am7 ай бұрын
    • @@Stealthy5am you know this could very well be an idiot munching the same chew gum as all others, and simply reproducing the brief summary of random arguments found online about preferring properties over fields

      @AlFasGD@AlFasGD7 ай бұрын
    • Except they made the property private which means it's not part of the public API.

      @pilotboba@pilotboba7 ай бұрын
  • I got all furious when I saw the title... All for no reason! :D This is the second time I've made that mistake, maybe I'll learn one day.

    @m4ster_root@m4ster_root7 ай бұрын
  • One benefit of private properties over private fields is that for properties VS codelens shows reference count which can sometimes be handy

    @paulp4061@paulp40617 ай бұрын
  • If you make the property public you can write nicer unit tests, the property should be auto mocked and you can "stub" a function directly by accessing the property field. (i did this years ago, but not any more)

    @IDrDoh@IDrDoh7 ай бұрын
  • Prefix/Sufix for classes and interfaces, _ for private members, UPPER_CASE for constants and $ for observables. This is the way.

    @mwzndev@mwzndev7 ай бұрын
  • Coding function and performance is the bias that I wirk to. I often don't use an IDE so the underscore is the standard i now use. It took me a couple of years to drop the m_ and just use the _. In fact i still have a couple of legacy libraries that still have the m_ in the code.

    @ianmcpherson2301@ianmcpherson23017 ай бұрын
  • Mocking and Testing is a reason to choose it. Not because of the implementation because this would probably be in the interface as a {get}. Not sure if newer versions of .NET solved Fields in interfaces but I'm still plagued with them for this, not like it's a big deal generally just writing {get; private set;}. Also some frameworks on the Mocking side only like Properties, sucks but happens. Notifications I can see but that's more... this is what properties are for... generally for like MVC. Probably included as it's a point for them not because it's a particularly good point.

    @ScottGarryFoster@ScottGarryFoster7 ай бұрын
  • It seems to me that the majority of the time stuff passed in the ctor would be readonly and a Field, as you wouldn't want it modified. Such as Dependency Injection. I would use a property if I needed that value public or protected. Otherwise the private readonly Field is the choice I would make. I also prefer the underscore in front of the name.

    @travisabrahamson8864@travisabrahamson88647 ай бұрын
  • I think one of the most telling things I’m this advice is they have a class named …UseCase. That I’m itself screams they’re clueless. I worked for a department once which actually had UseCase as the base class of every entry point to any action in a service. They worries too much about modelling things which weren’t necessary. Same here, thinking they have something to offer and chasing clout when they have no idea what they’re doing at the most basic level.

    @stephenyork7318@stephenyork73187 ай бұрын
  • Is it possible to see the low-level implementation in Visual Studio as well? Love the videos Nick!

    @VennieVin@VennieVin7 ай бұрын
    • It is! Just google how ;-)

      @igorthelight@igorthelight7 ай бұрын
    • @@igorthelight I’ve tried but can’t find anything, could you direct me to a link or summarise how? Cheers

      @VennieVin@VennieVin7 ай бұрын
    • @@VennieVin Tools -> Options -> C# -> Advanced -> Enable navigation to decompiled sources (and "enable navigation to source link and embedded sources").

      @igorthelight@igorthelight7 ай бұрын
    • Hey I really appreciate that, thank you!

      @VennieVin@VennieVin7 ай бұрын
  • One of the issues I have with primary class constructors in C# 12 is that you lose underscore for private readonly fields when having your dependencies in the primary constructors. I really like having my private fields be named with underscore

    @antonmartyniuk@antonmartyniuk7 ай бұрын
    • You don't have to lose the underscore. You can do this class A( string name ) { string _name = name; // uses name from constructor } Unless you use the "name" argument from the constructor in a method (or getter) it won't get a hidden backing field.

      @phizc@phizc7 ай бұрын
    • @@phizc you can do this, but the whole idea behind primary constructors is to decrease amount of code you write

      @antonmartyniuk@antonmartyniuk7 ай бұрын
  • Fun fact, the m_ came from c++ because way back in the day namespaces would use _ for interal stuff that would clash(atleast that is what my old teacher told me, not sure how true it is).

    @alexandernava9275@alexandernava92757 ай бұрын
  • I'm not a good fan to use underscore for private fields , but I understand your logic.

    7 ай бұрын
    • I Agreed.

      @supern4ut3@supern4ut37 ай бұрын
    • Well the alternative is the this. instead. I, on the hand, find that ugly but what ever coding style you like you can use. As long as it's only you on the project or you agree with the rest of the team that this is how you would name things. There is no right or wrong here, but there is a standard way of naming things and you can use it if you like it or use your own if you prefer.

      @CRBarchager@CRBarchager7 ай бұрын
    • @@CRBarchager You can just as well use standard camelCase and let IntelliSense do the work for you. It tells you whether it's a local variable or field. The main difference is the at a glance, which is the decision people have to make.

      @timmygoldstein@timmygoldstein7 ай бұрын
  • I think the versioning argument might be about ABI breaking behavior (at least something similar is true in some other languages. I am not knowledgeable enough in the CLR details to know if it applicable here though) Swapping between access control levels or switching between fields and properties can affect the ABI in some languages, which could have a negative effect on modularity and independent deployability. But based on some of the other arguments they gave maybe I am being too willing to accept they actually had good reasons. Sometimes private properties end up briefly in my code during the prototyping phase before the design has crystallized but I agree that they are a code smell. The only way they might make sense IMO is if csharp had protected or private interface inheritance, in which case a private property could form part of an extension interface for some sort of abstract base class. But even then the usual csharp convention would seem to be to make the protected, and as it stands this is something that shouldn't even survive a code review let alone be a recommendation.

    @timseguine2@timseguine27 ай бұрын
  • What they meant with version compatibility is that in the case you are providing a library, any code using your fields is going to break once you turn it into a property, and they'd have to recompile their code for it to work. So generally defining it as a property ahead of time would prevent this. However, this does not apply to private members anyway so this is completely pointless.

    @shalopo@shalopo7 ай бұрын
    • lol, I was about to point out private fields would not be accessible externally, then read your last line.

      @slipoch6635@slipoch66357 ай бұрын
    • But what if the caller is using reflection to access private members? 😛

      @EdKolis@EdKolis6 ай бұрын
  • I requested you that make a video on .NET Core, static file response compression. Pre-Compress (br / gzip) or run time by .NET Core or IIS. Which are best and how to implement

    @muhammadtariq8323@muhammadtariq83237 ай бұрын
  • It can be argued that never using fields simplifies C#, so there is less to learn. (You don't need to remember two different ways to make something readonly - you just don't add the setter instead of needing to remember to use readonly keyword vs not including the setter.) You can also argue it is simpler if you later decide to make that property public. Still, I doubt paying the (small) cost of using properties everywhere is something people should adopt by default - no need to lose performance if it isn't necessary. Personally I like using private fields since you immediately know from the naming convention that it is a private field instead of a property which could be public or private, so you get more information at a glance when reading. Of course, the main value in using properties comes when dealing with the interface of the class, so public properties (but also protected properties allow you to restrict the setter to private, for instance).

    @andrewmcclement4464@andrewmcclement44647 ай бұрын
  • There was a naming guidelines doc on MSDN a long time ago that said to forgo the underscore. I stopped using it and didn't even notice. The doc is no longer up.

    @JVimes@JVimes7 ай бұрын
  • Do you know why Microsoft has changed from m_ExplicitVarName to _ExplicitVarName removing the m which was there to specify "member" of a class ? I am an old software developer, and I still don't understand why they moved to another reduced naming convention. I would appreciate to know why. Thank you.

    @francoislepron2301@francoislepron23017 ай бұрын
  • This is madness! THIS IS CODE REFACTORING!

    @astrokotik6887@astrokotik68877 ай бұрын
  • I stopped using the _ in private fields because I can assign different colors to each member type in Visual Studio (Tools > Options > Environment > Fonts and Colors then search for User Member) I just have fields/properties in black, parameters in red-ish color and locals in navy color, it's consistent and I never run in the issue of forgetting an underscore somewhere. The only downside is that you need to use this in the constructor because parameters could have the same name as the fields.

    @FR12321@FR123217 ай бұрын
    • i guess you work alone on a project without pull requests. You also want readable code in code review on a webbrowser in the compare window.

      @jeroen7362@jeroen73627 ай бұрын
    • Readability of the PR in the browser was a concern at first, but so far (~10 devs, ~5 years doing this) there were no real issues I think some of the reasons for that are: - class names usually give a good idea of what the context is, eg. UserController, ArticleRepository, ... - fields names usually indicate functionality, eg. customerRepository, orderService, dbContext, ... - parameters names usually indicate data, eg. createCustomerRequest, userName, validUntil, ... - usually, it doesn't matter where an object comes from in a method as long as we can use it (and when it does, the issue tend to be in how it was injected and the lifespan it was given) This just my experience, definitely not a silver bullet but it works for us, colors are consistent even if you use _underscore :)

      @FR12321@FR123217 ай бұрын
  • I agree with you but 4th point compute or transform value is really useful. Let's say in a web project after 10 min session expire I can add Code in property getter most probably if condition if it's expire we will redirect user to login page

    @user-rw1ni5lz3e@user-rw1ni5lz3e7 ай бұрын
    • I think this is a bad design decision. Encapsulating behavior in properties does not make sense and can produce bad side effects. If it's an operation, be explicit an encapsulate it in a method.

      @rpenha@rpenha7 ай бұрын
    • @@rpenha sometimes you need to work in a project where there is no proper design and structuring they are only concerned to make the functionality work and you cannot change design so then these kind of things works pretty well

      @user-rw1ni5lz3e@user-rw1ni5lz3e7 ай бұрын
  • Geter instead of property recomendation is probably from time before readonly(or init) was added. Is not?

    @ondrejvrabek9485@ondrejvrabek94857 ай бұрын
  • I think the root problem of the post is that they used a *private* field in their example. Some of the reasons make sense when talking about public fields versus public properties.

    @vyrp@vyrp7 ай бұрын
    • And under the lens of public properties, I would interpret the "versioning" reason as being able to change the serialization of the data without changing the class API.

      @vyrp@vyrp7 ай бұрын
  • I see just one pros in private get property. It is a possible to set a breakpoint on getter. In multithread code it may be matter. Does private getter inline in runtime?

    @user-vm6ve1ze3h@user-vm6ve1ze3h7 ай бұрын
  • Private properties, as from my experience, were used only for lazy loading and not repeating this logic all over the places in different methods. In other cases, not really much you could get out of it. Plus thinking of private methods (usually its implementation layer already) usually you want to "hide" all optimizations over there, and having property won't let you operate with ref.

    @TheXX113@TheXX1137 ай бұрын
  • I always change editconfig to remove underscore from private field names and enforce camel case. I hate underscores, its so freaking MSVC++, its uncanny. There is a special circle of hell for people who brought it as a default into C#, especially with DI. You avoided having to use "this." in construcotr. Bravo. Ugh. If your attention span is so narrow or your method so complex you lose track which identifier is local var and which class member, you really should be looking for another job.

    @MilYanXo@MilYanXo7 ай бұрын
  • The underscore seems to be discouraged from VS sometimes. Maybe because I installed Resharper some years ago, but on my private PC, I cannot force VS to generate underscore for private members, and even in Microsoft documentation you can see private members starting with lowercase letters. I hope this won't become a standard.

    @etiennelemieux472@etiennelemieux4727 ай бұрын
  • You mentioned that we're supposed to use readonly in the field, why is that the case ? And what kind of scenario would i need to use readonly vs not need to use readonly in the field ?

    @kryloth3628@kryloth36287 ай бұрын
  • The underscore as first letter of a backing-field helps when you want the IDE to put it at the end of name-suggestion list (which appears while typing) … helping you to see the property before the backing-field.

    @anm3037@anm30377 ай бұрын
  • I had quite the good laugh at that picture.

    @artemisDev@artemisDev7 ай бұрын
  • One thing, which is not mentioned, is that the IDE typically show usages for properties but not for fields. I’m not sure whether that’s something you can enable in Rider, but it is sometimes useful to know how many times your field is accessed, which you just can’t for some reason.

    @KennethSiewersMller@KennethSiewersMller7 ай бұрын
    • There are two features in Rider I know of that might help. "Find usages", Alt+F7. The second is in the context menu after right-clicking the field, don't remember the name but allows to find value origins and value destinations. So you can find what uses the field or what sets the field

      @gabrielfkrk@gabrielfkrk7 ай бұрын
    • Shift + Alt + F11 / Ctrl + Alt + (PgUp | PgDown)

      @rpenha@rpenha7 ай бұрын
    • @@gabrielfkrk I know the shortcut to find usages, but what I’m looking for is the inline hint on top of properties where Rider shows the number of usages. You could argue, from a design perspective, that one shouldn’t have classes so big that it’s necessary to see the usages, but Rider is smart enough to know when a field is unused, so it must keep count somewhere.

      @KennethSiewersMller@KennethSiewersMller7 ай бұрын
    • @@rpenha yes, I know, it I’m talking about the inline hints Rider shows for properties and methods.

      @KennethSiewersMller@KennethSiewersMller7 ай бұрын
    • @@KennethSiewersMller I see. And I agree, that info must be there somewhere or easy to switch on (I mean for JetBrains devs). Hmm, I am now curious myself if there is a setting for that

      @gabrielfkrk@gabrielfkrk7 ай бұрын
  • Hi Nick, could you make a video on the Visitor Pattern? There is this one colleague that is pushing it in all the code, without really discussing it with any of the other devs. But I really don't see how the potential benefits outweigh the huge complexity bump in the code. But maybe with an explanation of you I could see it.

    @ThaWolloW@ThaWolloW7 ай бұрын
    • Gui Ferreira and Raw Coding have already a video about that. Maybe those can help you.

      @eqwerty610@eqwerty6107 ай бұрын
  • Can we get a video about class libraries using low level implementations like scanner, ocr, printers etc. Do you have libraries to use them on dotnet core? Cause COM references and IO references pretty hard to upgrade on .net framework to .net core. Thanks.

    @UnseenScofield@UnseenScofield7 ай бұрын
  • I have created a private property, but I did that because in Blazor, I wanted to Inject a service into a component, but I did not want that service exposed to the component users. And the InjectAttribute doesn't work on fields. I wonder if I could have injected it via the constructor? But then do Blazor components have constructors? *goes investigating*

    @KnightSwordAG@KnightSwordAG7 ай бұрын
  • Regarding "versioning", I suspect they meant you can substitute "{ get; }" with some computation logic without changing the rest of the class.

    @sergius_carp@sergius_carp7 ай бұрын
  • Private properties have their uses, like when you want a computed property but it needs to be private, or maybe your serializer only works with properties and not fields. I don't like fields much myself anymore, they seem like a relic. But replacing all fields with properties just to avoid underscores...

    @EdKolis@EdKolis6 ай бұрын
  • on note of giving advice just so you could give one, i have one "advice": one thing i see in code of others that they call async methods in succession even when they do not share data, they could be executed in parallel, if i'm not wrong, only thing they need to do is first create tasks and after that await them like var t1 = CallMethodAsync(); var t2 = CallAnotherMethodAsync(); var t1val = await t1; var t2val = await t2;

    @lordicemaniac@lordicemaniac7 ай бұрын
  • fortunately Nick chapsas exists

    @user-pk7tw4sk6d@user-pk7tw4sk6d4 ай бұрын
  • I like seeing how many references there are to properties, but yeah, not gonna make member variables properties.

    @AvgDan@AvgDan7 ай бұрын
  • For a very long time Microsoft didn't even have documented naming conventions for private fields. Even so, most C# shops adopted the underscore for the very reasons Nick says in the video. It helps you understand what's going on in the code at a glance.

    @ExpensivePizza@ExpensivePizza7 ай бұрын
    • Yeah as long as you have some standardised difference between public props, private fields, and method names you should be fine, differentiating from a class local field and a method local field may not always be needed but if you have any disposables happening I wouldn't want to go without that either. I'm not a huge fan of _ but I use it.

      @slipoch6635@slipoch66357 ай бұрын
    • And some of us are so old school we use camel case for fields...

      @EdKolis@EdKolis6 ай бұрын
  • Feels very much like somebody churning out content from a LLM and either not checking it or not understanding it in the first place.

    @tangomoocow@tangomoocow7 ай бұрын
  • I like using _ or this IDK why people sometimes consider it ugly. I think it also helps programmer name more variables.

    @asagiai4965@asagiai49657 ай бұрын
  • One vote for the other guy would be that I can override a virtual property ( that has a get accessor) with a covariant return type. Granted it wouldn't be private

    @ratherbyexploring4898@ratherbyexploring48987 ай бұрын
  • If you don't like underscore use pascal case. When i'm working on a method I don't see a need for knowing if a name is a field, property, private, public, virtual, inherited, injected, .... Why should i waste time by decoding the name of a variable, when I just need the value?

    @Krauttrooper@Krauttrooper7 ай бұрын
  • I still don't understand why some people would use a global service like linkedin to post their personal coding preferences. We all have different styles of coding; some good and some bad. Thanks Nick, for keeping us informed.

    @iSoldat@iSoldat7 ай бұрын
    • It's quite simple, the goal is not to spread technical knowledge or spreading an opinion, the goal is to increase visibility and followers so potential employers might get the idea that you are an impressive developer, netting you better career prospects or the chance to convert your following into money.

      @allinvanguard@allinvanguard7 ай бұрын
  • While the reasons the author of the original post listed were, for the most part, pretty silly (as you point out), I do favor properties in most cases for one reason. In fact, you even demonstrated that reason without knowing/mentioning it! When you had the field and the property both present in your demo code, notice the 'guide' above the property that says '1 usage'. In Visual Studio, clicking on this guide shows where the property is referenced. Fields have no such feature (I don't know why, Microsoft should add this). So, simply as a convenience, properties make development easier because they have better IDE support.

    @bradoestreicher3476@bradoestreicher34767 ай бұрын
  • Don't most IDEs highlight private member fields with a different colour? In Visual studio class member fields and local variables are in different colour, so I've never felt the need to add an underscore.

    @zhivkoaleksandrov3277@zhivkoaleksandrov32777 ай бұрын
  • Only reason i use private properties is when i need to do something with other fields or also change another field. For example Fullname with only a get that uses firstname and lastname to create fullname.

    @dannym817@dannym8177 ай бұрын
  • There is a reason why private properties can make sense. You can differentiate them from private fields and what has been injected. Of course, this is a bit weak, naming convention can overcome it. On my private code bases, the style has changed towards private fields, but there is definitely some mess in older libraries. Stopped doing logic inside setters/getters years back - maybe with vba. Have seen all manner of variations and am not going to go ape over it.

    @mrwillis5339@mrwillis53397 ай бұрын
  • I clicked on this video not even imagining the suggestion was going to be to make a private get only property ... wow, that's crazy.

    @WilliamCWayne@WilliamCWayne7 ай бұрын
    • For an injected member, no less!

      @WilliamCWayne@WilliamCWayne7 ай бұрын
  • XD

    @Snikersano@Snikersano7 ай бұрын
KZhead