C# – Organizing Class Members by Access Modifier

access-modifierscclass-designcode-organizationobject-oriented

If we look at typical implementation of a Class, we usually see the private members defined at the beginning and public( mostly functions and Accessors) defined towards the bottom. Now, is this a Industry standard agreed by a lot of people?

How about keeping the private members towards the end as updates and additions are usually done to the Public Members(mostly functions), to fix bug or provide enhancement, so we don't have to scroll down towards the end to get to the function definition section.

I understand, good IDEs will allow us to Jump towards a specific attribute, but considering other factors, such as Code Review, it may be convenient to have the Public Definitions towards the beginning.

What is the most accepted standard for Class Member Organization?

Best Answer

so we don't have to scroll down towards the end to get to the function definition section

If you have so many private members in a class that you need to scroll down far, you might want to look at the design of the class. I don't think you'll find that the biggest problem is whether you placed the private members at the top or the bottom.

Or, to put it another way, if the sequence of definitions in your classes is really the biggest problem you have to solve then congratulations, you have a great code-base, and you should just get on and develop business functionality, rather than worrying about these kinds of details (which, as you point out yourself, your IDE worries about for you).

That said, if your private members are simply backing members for public properties then the simple answer, in later versions of C#, is auto-properties -- but if you need them then they're probably better hidden away at the bottom.

If you are using them to encapsulate abstract services, then I would prefer to see them at the top so that I know, as soon as I enter that class, what kind of dependencies it has.