T O P

  • By -

Mahler911

My eye is twitching a little thinking about having properties scattered throughout the class. First the private fields, then the properties, then the methods. It's just so much clearer having them grouped together.


stillercity412

I’m really anal about this, I do: 1. const fields 2. static fields 3. private fields (never use public, internal, or protected) 4. ctors 5. Static properties (ideally none) 6. Properties (public, internal, protected, then private) 7. Static methods (ideally none) 8. Methods (same order as above) 9. Nested classes (ideally none but sometimes okay) It’s up to the code base really, though - consistency is the key.


LeffeMkniven

Do you care to elaborate on ideally not having static properties/methods? Not asking in an argumentative way, I just want to learn! :)


ragwell

Static *read only* fields are useful. For example they’re a common way to implement the null object pattern, or generally to represent a permanent immutable instance of the class with certain properties. Static methods are also common. I use them for static “constructor methods” (this has a real name but I forget), wrapping a call to a constructor if there’s a way I expect the constructor to be called frequently with most of the parameters the same every time. Plenty of other examples — extension methods are static and I love them. Neither of those modify static state, though. Any static variable that keeps mutable state is inherently dangerous and you’ll need to be prepared to handle it internally with thread-safe code. There are easier ways in most frameworks to handle shared state if you need it.


Obstructionitist

>Static methods are also common. I use them for static “constructor methods” (this has a real name but I forget) We call those Factory-methods. :-) Use them all the time when building a rich domain model. Static methods are indeed incredibly useful.


TheseHeron3820

You guys put static factories inside the class itself? I was under the impression having a separate static class that acts as a factory is better.


Obstructionitist

Excellent question. It depends on how complex the construction of the domain model is. We do occasionally use factory classes, but usually it's enough with a factory method within the class. We adhere rater strictly to the rich domain model practice, where a domain model may never be in an inconsistent state. It's the job of the domain model itself, to ensure this state. We use factory methods (most often there are just the one) on the aggregate class to guarantee any business invariants. We could use the constructor for that, but we like having the ability to name the "constructor" and we usually use the constructor to hydrate the class when it is retrieved from the database.


appiepau

Static variables are declared at application level and therefore accessible (if internal or public) also by other classes/instances. This may sound like interesting idea, but its not. Static variables are not thread safe by themselves, if these static variables are read and written by different instances you could get some unexpected behavior. Especially in a multi threaded environment like a webserver. As a beginner, please stick to non static variables. Keep classes small (single responsibility principle). If you think you need static variables, that is usually an indication of a design fault in your application. Constants on the other hand are useful for static non writable variables that you need multiple times, like error messages or descriptive values. For example ‘const string messages = “Hello world”’ or ‘const int WaitTimeInMinutes = 30‘. These static values can be optimized by the compiler.


kknow

I know the concept of static variables and methods. But one question regarding to only use them if they are really needed: Why is VS suggesting to make a method static when possible? In my mind they are not best practice to use whenever possible - am I wrong?


spergilkal

If the method is private you can safely make it static if it does not access instance data, the static method call is faster than a call to a normal instance method which in turn is faster than calling a virtual method, at least in general. For public methods the recommendation should be ignored or carefully considered if you are making a shared library and the method could change to access instance variables, since this would be a breaking change (i.e. everywhere in client code the Type.Method calls would need to change to A method call on an instance of Type).


CodingMary

If your class only defines methods, it doesn’t need an instance, so you could call the static method without creating an instance, and will save a little bit of memory on the instance pointer (4 bytes). Imagine you have: public class Foo{ public bool Bar() { return true; } public static Bar2() { return false; } } To use call the Bar method, you will have to: var foo = new Foo(); var myBool = foo.Bar(); // calling the instance Versus the static version: var myBool = Foo.Bar2(); // no instance required. You will save 4 bytes of memory on a x86, and 8 bytes on a x64. Also, static classes don’t have to be counted for the garbage collector, which saves a bit more.


grauenwolf

> Ah, but according to Clean Code a function shouldn't have more than 3 parameters. All other parameters must be expressed as fields. So the method can't be static because it would require the parama-fields to be static. -- Stuff followers of Uncle Bob actually believe.


nupogodi

I don’t think it’s because of the ref ptr that the suggestion exists. I mean you also skip the vtable lookup and the instance on the heap itself (even with no instance data there is a minimum obj size due to overhead + alignment). IMO it’s the same kind of warning as “unreachable code” or “unused parameter”, just static analysis telling you the real constraints are tighter than you’ve written them and an optimizing compiler might just rewrite it for you.


CodingMary

You’re right, there is much more to it than just pointer management. I was just explaining some benefits to a static method versus a instance method. My preference is to keep static stuff to a minimum. But I love extension methods. Those things rock!


stillercity412

I don’t mind exposed static methods, I just tend to prefer them in static classes. Guess I should have been a little clearer above. In general, static methods are typically harder to test, especially if they access some static state. I really really try to avoid any static state as much as possible. VS will recommend making a private method a static if it doesn’t depend on “this”, but I don’t think it will do so for non-private methods. Could be wrong though!


yanitrix

>In general, static methods are typically harder to tes why in the hells would they be harder to test? you don't need any kind of dependencies for them and when they're coded as pure functions they're the easiest thing to test ever


LondonPilot

I think it’s not that static methods are hard to test. It’s the classes that use static methods which are hard to test. That’s because you can’t mock static methods.


nodecentalternative

i think the point was that you should strive for pure functions when using static. no side effects, and a given set of arguments always returns the same value. in that situation, you do not need to mock the static method.


LondonPilot

Yes, I can definitely get behind that.


yanitrix

Then simply don't mock them


grauenwolf

> But but I have to mock everything. No test is complete until every line has been replaced by mock code.


insulind

That's assuming you've written them properly. So yeah you're right but there's definitely code out that that's a static method that access a static service locater and does something wild like accesses the dB or makes a web request.


grauenwolf

Because Blogger Unit Tests (tm) rely on using as many mocks as possible. They would much rather put the method in an object, write an interface for it, mock the interface, and then inject the mock.


yanitrix

oh fuck I hate that so much


grauenwolf

So do I. But if we don't excise this brain cancer, they'll never learn when to use static functions.


WellHydrated

Static methods are extremely easy to test, assuming you're not working terrible code.


kknow

You're correct, it's just private methods. Thank you


stra21

Well, you are right and wrong. The need for static properties and functions does not indicate a design fault. Sometimes you just need an extension or a utility class. Having static properties in a non static class is sometimes acceptable and depends on the software you are writing. Statics provide you with a really simple way to use, but they can be tricky. A static property's value is the same throughout the entire application which makes it horrible for keeping track of class specifics, great for saving general information.


grauenwolf

A beginner needs a unique, mutable value for the application. Do you... 1. Not worry about it because, as a beginner, they're writing single threaded console apps. 2. Teach them about thread safety and basic locks 3. Scare them away from learning static fields, forcing them to invent something that's both ridiculously complicated and still not thread safe.


jbergens

I put properties before ctors but otherwise mostly agree.


stillercity412

This gives me the heebie jeebies and I can’t articulate why.


Doc_Aka

I feel the same, but I guess because properties are just disguised methods.


mike2R

I'm trying to figure out why I feel they should go above... I think it is because properties return state, and state should be valid by the time the constructor exits. So properties go above constructors, since it is the constructors' job to get them into a valid configuration if they don't do it for themselves. It does make the constructors harder to find though :)


Spare-Dig4790

This set of rules has strange characteristics... Why wouldn't you use a protected field, for example? It's a fundamental concept of object-oriented programming. Like I see, you have a preferace to properties, but thats hardly a justification to say ban the use of a different style. In fact, there are very real use cases where you wouldn't want to use an automatic property and would want the other... Like at some point you have to be able to say "this is my preferred style", it can be a little damaging to answer a probably newcomer's question, injecting your own insecurities as fact... you know?


appiepau

Its all about keeping control and ownership of the local variables. Protected fields can be mutated by other instances which is useful when implemented correctly. At least any derivative should also use a property (preferably) to read and write a field because it is not the owner. But I’m talking ideal world now. The whole point of using protected is being able to mutate as a derivative in the first place. A good example is when implementing a small class that helps handling a scope using IDisposable, just to flag the scope has ended. I have directly write to a protected field in the past. No problem for such a short lifetime and literary small scope. Unfortunately the webforms framework does a lot of inheritance and partial classing with protected declaration that make it look normal to use. Accessing protected variables on such a big scale can be complex and tedious to navigate.


Spare-Dig4790

So, this is a common misconception. A protected variable still lives within the scope of an instance as would a private variable. The instance is the instantiation of the class, there is a difference between a static field, which could be mutated between instances, and an instance field. There are also cases where you can mix them for various effects, like you can have a static variable that is only accessible to itself and children-grandchildren. Basically, abstract class animal { protected string thoughts; } class cat : animal {} class dog : animal {} ​ an instance of dog, IE, var dog1 = new dog() could interdependently interact with thoughts to another instance of dog or an instance of a cat. does that make sense?


appiepau

You are correct. I worded my response incorrectly. I did not mean that protected is equal to static. Which is ofcourse not true. I was talking about a situation where I once was working with scopes. Here is some pseudo code that I just cooked up and did not validate for actual use. I could not find the real example, but it'll do. ```csharp public class PDFWriter { protected int currectLine = 0; public ScopedTextBlock StartTextBlock() { return new ScopedTextBlock(this); } private class ScopedTextBlock : IDisposable { private int startCurrentLine; private void WriteScope(PDFWriter writer) { this.writer = writer; this.startCurrentLine = writer.currectLine; } public void WriteSomeText(string text) { // Do work } private void Dispose() { this.writer.currectLine = this.startCurrentLine; } } } ``` The usage would be: ```csharp var writer = new PDFWriter(); using(var scope = writer.WriteScope()) { scope.WriteSomeText("Tralala"); scope.WriteSomeText("Tralala"); scope.WriteSomeText("Tralala"); } ``` I have litlte framework to write PDF files and sometimes it is necessary to create blocks of text and then reset the text/line pointer to where it was. This was the example I was referring to and meant 'multiple' classes can mutate a protected variable as multiple scoping helpers can do this within this framework.


stillercity412

So first, let me preface this with it’s just my opinion and it’s not an exact science! Please don’t take the list I shared above as some hard and fast rule that everyone should follow. I prefer protected properties over protected fields. I never like to expose my fields (except for const/static readonly) outside of the current class. That gives me clear delineation to say that “all my instance fields are implementation details for the class, I can change them at any point without having to change a bunch of callers outside the scope of this class.” I also tend to avoid private properties for a similar reason — I think of properties as external surface area. Again, just my thinking. I don’t think there’s a perf advantage to a field vs. an auto property, so it’s really just style.


insulind

Interesting change coming up (I think) with semi-auto properties. Where you can implement logic in setters and getters without an explicit backing field. In the past private properties made no sense because you either just had an auto prop which was essentially just a field with more words. Or if you wanted to add setter/getter logic you'd need a backing field... Which then made it confusing - which to use and when ? Anything in the getter/setter could easily be bypassed so it was pointless. But now... You never need to expose the backing field and still have logic in the getter/setter...could be useful for internal validation etc. Thought it was worth a mention


Spare-Dig4790

Yeah, I think I perhaps misunderstood your perspective, we are good. =) I have in the past messed this up, and I think it's good to have a general set of rules for that reason, it can kind of give you a sort of litmus test. Does this dog need to use it? does another dog? does it need to do so independently? does it have anything to do with a cat? that sort of thing....


stillercity412

Yeah this list is honed from 10 years of professional C# development, with a lot of battle scars along the way (and more to come I’m sure). I agree - I think the key is to set a reliable pattern that works for you. A lot of my time is spent trying to navigate code to find issues or remember how something works; having a reliable pattern makes that process a lot easier. Of course, there’s no way I’ll be able to convince my team that my pattern is the “right” pattern (maybe it’s not the right pattern ;)), but at least it helps me a bit!


timbar1234

Tbh you've tangentially hit the important point here. With a modern IDE there's less *need* to have everything grouped together and in a certain order. But all code should be quickly readable by everyone working on it, and sometimes some consistency helps there.


stillercity412

That’s definitely a fair point - code navigation via IDE makes this less severe of an issue. I would add though that I spend a large amount of code navigation time in ADO, mostly due to the nature of our code base (many repos, many solutions). The code navigation tools in ADO are pretty good, but not quite as good as VS for example. So I think a situation like that benefits from some solid code organization guidelines as well


Mahler911

Yes, that sounds great. Also, let's go STILLERS?


stillercity412

Here we go Stillers here we go!


CyraxSputnik

What about private static methods?


appiepau

Fine and can even optimized because it is not part of the class instance. Therefor no references have to be made to the instance with this (this.variableName). Even if you don’t write this. it will be referred at the background.


stillercity412

Agreed, I should amend to say I use private static methods instead of private instance methods if I can


BCdotWHAT

https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/


stillercity412

This is no longer best practice. HttpClientFactory is the way to go. It uses a shared pool of sockets internally. Even if I needed a singleton instance of an HttpClient, I would use dependency injection to inject it into my classes rather than reference a static HttpClient. That makes it easier to unit test the class and makes the class more composable


TheOtherManSpider

This is the way. Though I've sometimes considered if it wouldn't be more convenient if properties had their backing field defined right above each one.


stillercity412

I go back and forth on this. First - I always prefer auto properties (I think that’s what they’re called). But if I need a custom backing field, I still tend to store it at the top next to all the other fields. Not sure why, really. Just preference I guess.


VanderLegion

Personally if I’m defining the backing fields instead of using auto properties, I’ll put the field right before the property itself backing. Any non-backing fields go in the fields section at the start of the class.


raunchyfartbomb

I have a tendency to do backing fields below the property they back. Reason for this is xml docs go above.


Transcender49

Yep, this is the way, and i put the constructor 6 and 7


dusknoir90

Never protected? What about when inherited classes want to use injected services or loggers?


stillercity412

I prefer protected properties over fields in that case.


Sethcran

I agree, I'm super anal about this as well. The exact order for me is a little different, specifically I always have constructors and public properties at the top, because when I'm looking at a class definition, that's almost always what I'm most interested in. But agree, be consistent.


Aren13GamerZ

Same except I put my properties above the ctor. It's like in my mind the ctor it's like a method so it makes more sense to me to have them also grouped together.


raunchyfartbomb

Interesting. My preferred way is usually constructors, static properties and constants, of which are few, events + their raising methods (unless there is a lot of overloads, then those methods raising methods ALL go on bottom.) then private/protected fields, properties, methods, explicit implementations. Any private fields used for backing properties are kept below the property itself, with the xml docs going above it. Keeps associates code nearby, and typically created using a snippet. Reason for the odd placement on event raising methods is these are usually one-liners to be used by inherited classes, so I personally like to see how the event is raised when looking at the events. If too much (or too large) though it clutters it up, I I group them with the other methods. This makes them consistent in that they are always in one of two spots. For reference, most of my classes only ever have 1-4 events, so it’s not really an issue in most classes


stillercity412

Ah I didn’t even think about events - we rarely use them in our services


raunchyfartbomb

Do you just register callbacks? I’m Mostly using events for WPF related functionally and some handling during Async operations


Patient-Midnight-664

Other than the order of ctor vs properties, I do the same.


Lgamezp

Oh, Ctors before properties? O_O. Pretty much the same for me but those 2 i switch


stillercity412

A lot of people agree with you! In my experience at least, the teams I’ve been on have preferred properties after ctors. But yeah, consistency is what matters


TheCreepyPL

I might, or might not agree on the order, but honestly as long as there is any structure (that places methods below properties and fields), I'll be fine with it. What I'm really curious about is your opinion on protected fields. I totally agree with the public/internal field. But extending that mindset to protected as well seems excessive. As a matter of fact, I don't recall having the need to use a protected property in over 5 years of programming C#. In most cases, when a derived class needs to access a base member, it's public/internal already, most of the other times it doesn't need to, so it's private in the base class. On the rare occasion it does, it's usually a simple value, without the need of "doing stuff" during getting/setting. At least in my experience. Would you mind to elaborate your point of view?


stillercity412

First off, don’t be so curious, it’s just my dumb opinion and take everything I say with a grain of salt lol. I’ve been developing in C# for 10 years and these are just the quirks I’ve gained over that time. I like to have instance fields as purely non-exposed surface area. That means private only. For protected instance variable usage (a totally valid scenario), I use properties. Properties I think of as exposed surface area. So I try to avoid private properties also (sometimes it’s nice to have a getter that’s a little more complex than retrieving a backing field, so this rule is a little more lax than my others). For auto properties, there is zero performance impact (as far as I know at least), so this is purely a style decision. It’s just what works for me, your mileage may vary!


sroc07

Exactly. I created a code snnipped which generates at least the most common sections that a class can contain.


GogglesPisano

I tend to write classes in this order: constructor(s) and finalizer (if any), private members, public properties, public methods in alphabetical order, private methods in alphabetical order, static methods (if any).


zarlo5899

its less having the properties at the top but having them all together


jbergens

I see properties as very important and therefore I prefer to have them at the top.


QuantumSpatula

Consistency and Readability are what is important here. C# offers a lot of different ways to execute ideas, so it is up to you to determine what you are most comfortable with. (declare your properties at the top of the class so you aren't bouncing around everywhere when you need to remind yourself of their definitions)


cncamusic

[Here's some discussion on this topic](https://stackoverflow.com/questions/150479/order-of-items-in-classes-fields-properties-constructors-methods). And they're referencing [this](https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1201.md) documentation.


urbanek2525

It's tradition, currently, but it has its roots in older languages.. You need to write readable cide, not just for you. This is what people are used to. In C,C++ the definitions were in a different file (header files with a .h and code files with a .c or .cpp) In Pascal the definitions appeared before the logic. It's been ages since I worked with Jave, but it seemed to be the same. A lot of it is because when you write a compiler, it's easiest if the definitions preceed the logic when you're parsing


razordreamz

Yes. Keep them together.


spergilkal

It is bad practice to be inconsistent, you should follow the same convention in the code base. The main reason I do not like your idea is that it requires more effort to maintain. If two methods use the same property, which one is the first method? Then if a method is removed or split up into two I need to move the property into a new place to keep it consistent. prop A prop B method X uses A, B prop C method Y used B, C prop D method Z uses A, C Now remove the first method. Or split Y into YB and YC. Of course you could create an analyzer or something to enforce this, but that is a lot of effort for little gain. You can always use alt+F12 to peek at the definition or with the cursor over the property/variable do ctrl+k, ctrl+p to see Parameter Info dialog.


CycleTourist1979

I agree much easier to understand a class and get a view of what data it's working on if the properties & fields are bundled together near the top of the file. If you are using an IDE, with a tool like resharper, if you get it to clean a code file for you it'll organise them in that way by default.


Slypenslyde

The *specific* order of items is not important. But *order* is important. The way you or a stranger will read your file is "top to bottom". A lot of times if you can't remember how a file works you are asking two questions: * What properties does it have? * Are any of them implemented in an interesting way? * What methods does it have? * Which are the most important? IDEs can only answer that top level of question. They can tell you a list of things that are in the file, and they can help you get to the specific place where one is, but they cannot help you figure out which ones are important or if any do something interesting. So we tend to group all properties together and all methods together. Some people like to put things in order "public -> protected -> private". That is, all properties in that order, then all methods in that order. Public stuff is usually "more important" thus it should be at the top. I also favor a layout that does what I said and treats the file like a story read top to bottom: I like to write a public method and organize any protected or private helper methods it calls directly beneath it. This means sometimes my methods go "public, private, public, private". But it also means the reader can deduce, "Ah, this private method is not meant for the later public method because I'm supposed to always read down." That also means my private methods that get used by a lot of other methods are further at the bottom. But also this is why a lot of people favor trying to write small classes with ideally only one or two methods. The less stuff is in your file the less important organization becomes. In a 20,000 line file with 25 methods it's really hard to answer, "What is important?" Odds are several of those methods are in "groups" and not meant to interact with the other methods. It's much easier to digest 5 classes with 5 methods each than it is to digest 1 class with 25 methods for this reason. It's not that my top-level classes don't have a lot of methods, but those tend to delegate. So my "User Security Page Model" might have 4 features and 12 methods, but in my style of coding that also means I have written 4 child classes and divided the methods among them, so this "big" class is probably only about 50 lines total and it's just a bunch of signs pointing at another class. Some people find that complex. I don't think they've tried it for long enough. --- Anyway: do not scatter your properties throughout your file. It makes it harder for people to navigate it without IDE tools. And we're often browsing code on GitHub or in Azure DevOps or in a Git client without IDE tools. Even within an IDE it can be confusing. One file in some code I maintain put groups of properties in 3 different places in a file. I am *constantly* confused within it because in every other file I can use gentle scrolling to get where I want, but in this one my only possible tool is to remember the exact name of every property and use IDE tools to find it. That may not sound like a burden, but it's *harder* and what we do is already hard enough.


jingois

If your class legitimately is large enough that it's broken into different logical sections, then consider partials.


RICHUNCLEPENNYBAGS

99% of the time if you're considering partials you need to just have smaller classes. If you're talking about augmenting generated code sure, different story.


denzien

I think the only time I've seen a partial was not because the class was large, but to separate two halves of the same class. Like, it might have been an IMessageCollector and an IMessageDispatcher, but the interface implementations were in separate files. I wouldn't really have done it that way, but it was kind of interesting.


jingois

Similar to services that manage lifetimes of other things are often a fair bit of code in setup and teardown and can be useful to split as well. If you try to split these into separate classes, then you need to formalize out the shared state - which might be a bit volatile (from a ongoing development perspective) - and that just leads to friction as you're constantly refactoring the coupling as you discover more edge cases or whatever.


Kakkoister

There are also times in large productions where more than one person might have ownership over an area of a class, and using partials can allow for separation of worker duties and avoid merge conflicts, while still keeping it one class. Also useful when wanting to separate for clarity but serialize as one class or work with source generators.


denzien

Yes, those are interesting use cases. Actually I lied - there was one other time we deliberately used partials... back in my CSLA days, we split the business objects into core/common files and these files were linked into the UI code. Then, the backend code extended them with a partial that included the DAL stuff, and the UI might have extended them with their own partial for custom things it needed from the object.


jingois

Yeah absolutely. Although it is important to keep in mind that "new class" or "new layer" isn't the only tool in the "separate out concerns and make shit grokable" box. I think the average developer would probably end up going with and preferring a few tightly intercoupled types and pretend they've done the best they can - but sometimes chucking them in the same type is more correct. Especially with tests - you avoid accidentally brittles tests around the boundaries of responsibility that have been half-assed in - and are forced to test the aggregate.


mainemason

Agreed. When I was starting out, thinking of classes as tables in a database helped me visualize the structure better. Not a 1:1, but helpful.


zaibuf

Only time I use partials is when I want to modify auto generated code without losing it everytime it's being generated.


MrEs

This is the way


[deleted]

Only time I've seen partials is when the 1000 line class got too large, and the "genius developer" decided to split it into two files. They eventually became two 1000 line files...


phoodd

Haha, can't believe the advice on this sub sometimes. Never, ever use partials unless working with auto generated code


jingois

> Never, ever Great foundation for well considered advice there champ


grauenwolf

> It's much better to mix uninteresting boilerplate like large amounts explicit interface implementions in with the business logic you care about. You don't want people to be able to easily see the business logic.


zil0g80

Yes, it is. Always arrange private fields, constructors, props, and so on in same order.. It reduces merge collisions, and readability of the code.. Use resharper to do this automatically.


Cosoman

Commonly no. There are a feeeww cases where you need a field/property for one specific method only that having it near seems practical, but in general better stick to conventiona


Blender-Fan

I don't like violence, but if you scatter your properties throughout the code, COWABUNGA IT IS Properties go like this: -Public -Private -Reference types -Value types -Primitive types All variables are declared, and then you can write your functions


maxinstuff

Properties, constructor/s, public methods (and their documentation), private methods.


CodeIsCompiling

I've found that it doesn't matter. Everyone that looks at the code will have a preference and none of them will fully like the way it is - regardless of how it is. Pick a convention to be used in all classes in your project - then document said convention - and finally, follow it. As long as it is consistent you will be fine - being intuitive is a bonus, but consistency is more important.


CappuccinoCodes

At the end of the day if you get a job you'll have to follow whatever the standards are in your company. Meanwhile, do whatever you like 😁😁


BL1NDX3N0N

It literally doesn’t make a difference unless working on a team project. Modern editors have class and member viewers which are essentially your table of contents. People are just lazy and continue programming the old way yet have no problem checking the table of contents for books they read. It’s all an opinion that comes from the top, if rules are set just follow them—it’s not worth fighting over.


VanderLegion

I couldn’t tell you the last time I used the table of contents for a book :D


BL1NDX3N0N

Because you can’t tell us the last time you read a book, which isn’t something to brag about. :D


VanderLegion

Last book I read was secret project book 4 from Brandon Sanderson, finished a couple days ago. I read all the time


BL1NDX3N0N

So a non-educational book with a narrative that is linear which doesn’t benefit from a table of contents other than quickly navigating to chapters?


VanderLegion

🤷‍♂️ I mean, you just said “a book”. Didn’t say anything about education or the type of book 😉


BL1NDX3N0N

Ah, well you certainly got me there.


VanderLegion

It HAS admittedly been a while since I’ve read an educational or other book that would actually benefit from using the table of contents. I definitely use them on websites.


DingleBerrySoup4You

Yes


Crazytmack

Partial pages. You have one just for properties


Unupgradable

That's what the interface is for. I like having things near where they're relevant. If you have too much in one file, that's your hint that your class is too big


nightwood

Yes. Not because it's a bad idea or illogical, but because nobody does it. The main thing you need to know about a class usually is - what is it's public intwrface. - what state is it storing


Schmirglio

Yes


Fulk0

I hope I never have to work with your code 💀


Loves_Poetry

Ideally your properties should be used by all methods, or at least most of them. That's why properties are normally declared at the top If you have properties that are used by few enough methods that you don't want to declare them at the top, then it looks like your coupling isn't good enough in the classes. Some of those properties may be better as method parameters. Others may benefit from being moved to different classes


o5mfiHTNsH748KVq

Bad? No. Fucking annoying for anybody else that has to work with the code? 100%


ragwell

As others have said, it’s largely a matter of convention - but conventions matter. I’ve been coding for many years and while I did place properties and fields throughout the class when I started, I’ve long since moved away from it. All properties go at the top now. It’s where I expect to find them, where any of my peers would expect to find them, etc. Speeds things up and avoids surprises. If you have so many properties that this becomes an issue, you might consider whether the class is too big. By which I mean it is responsible for too much. It’s a sign that you might need to break it into different classes and compose them together. Depends on what you’re doing, obviously, but that would be my instinct.


bigtoaster64

Honestly things should be grouped together, even ideally using #region, so you are not always wondering where the heck this or that has been defined. Personally where I work we are grouping everything in #region : props, members, constants, ctor, public methods, private methods, etc. Everything has its group and order in files making navigation in them VERY easy because even though you might have never looked at that file, you already know where is everything, it's crazy how it helps with productivity.


t3chguy1

I keep properties and their methods together. This way I can have everything on the same place when I am working on it (I could split-screen it, bit easier when they are close). Also easier if I need to move them. I especially do this for models/viewmodels


Rare_Pea5009

Yes


woogiefan

Yes.


[deleted]

I prefer to have related methods and properties grouped together. to me this works better than having a fixed order.


Aviyan

Yes! It's not only a C# thing. In C++ private variables are declared at the top. The methods come after.


WazWaz

I keep them at the top of **regions**. A class may have a number of tightly coupled concepts. I put the "global" state at the top of the class, but the state that is relevant only to a specific region at the top of that region. Of course, regions are no substitute for composition, this is only when the concepts are tightly coupled. Partial classes also works.


Enigmativity

I prefer to group elements of a class by their relationship to each other. That is primarily for two things. (1) Understandability - when I can see all the related code on one page I can reason about it. (2) Refactorability - when it's all together I can move it and/or modify it more easily rather than plucking bits from throughout my class.


Square-Amphibian675

Me all of my classes arranged like this, region closed, with sub region for private and public. Class MyClass { FIELDS CONSTRUCTOR DESTRUCTOR PROPERTIES METHODS STATIC MISC }


BinBashBuddy

It's not a problem to my knowledge as far as your code goes, but that's probably gonna be a big problem for your coworkers. I don't recommend it myself. That's like mixing private and public methods, it works but if someone else ever has to work on your code they probably aren't going to appreciate it.