✅ Question about partial classes
So recently I got into partial classes (it's a miracle I didn't find out about this sooner I love them) and have since been using them to manage my code by splitting up classes into what they do /take care of instead of having one huge class
Now I wonder when and when not to use partial classes because personally I don't see any downsides to them, for example when writing a library that uses partial classes, doesn't that mean people can easily write an "extensions" by tapping into the same namespace / class and just adding things to them
8 Replies
if your class is so big that you think you need to partial it, it's too big - if your class is doing too much then write entirely separate classes
and partials only work within the same project, you can't add to partial classes from another project
it's most useful with source generation, because partials allow the source generator to add code to the class you're writing
besides that they're more of a code smell than anything
Interesting
How do packages like Dapper manage to "insert" themselves into other packages
Cause to my knowledge none of the SQL packages like SQLite, PSQL, MySQL etc have a built in function Query<T> on the connection, but with Dapper they suddenly do
those are extension methods, not partial classes
Extension Methods - C#
Extension methods in C# enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
which are syntax sugar for something like
MyStaticClass.DoSomethingWithAnInstance(theInstance)
That's interesting
Also to explain my usage of partial classes
For example when I'm writing a client for an API I see no point in having a class with 4000 lines of code that does all sorts of stuff when I can split it into multiple files that take care of the different parts of the API, this way it stays 1 client but its way more maintainable
there are still ways to compose that out of separate classes
but i don't know what api you're working with
There are mulitple so that's kinda my general workflow
I mean I do split classes when it's needed but on a user level I find it easier to have this Client object hat fulfills all my needs while on the backend of it I can manage it like that
Anyways I think my question is answered :soPortuguese:
Thanks a lot! Much appreciated