C# classes in separate files? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Should each class in my C# project get its own file (in your opinion)?

While the one class per file policy is strictly enforced in Java, it's not required by C#. However, it's generally a good idea.
I typically break this rule if I have a very small helper class that is only used by the main class, but I prefer to do that as a nested inner class for clarity's sake.
You can however, split a single class into multiple files using the partial keyword. This is useful for separating your code from wizard-generated code.

Files are cheap, you aren't doing anyone a favor by consolidating many classes into single files.
In Visual Studio, renaming the file in Solution Explorer will rename the class and all references to that class in your project. Even if you rarely use that feature, the cheapness of files and the ease of managing them mean the benefit is infinitely valuable, when divided by its cost.

As others have said, one file per type in general - although where others have made the public/private distinction, I'd just say "one top-level file per type" (so even top-level internal types get their own files).
I have one exception to this, which is less relevant with the advent of the Func and Action delegate types in .NET 3.5: if I'm defining several delegate types in a project, I often bunch them together in a file called Delegates.cs.
There are other very occasional exceptions too - I recently used partial classes to make several autogenerated classes implement the same interface. They already defined the appropriate methods, so it was just a case of writing:
public partial class MessageDescriptor : IDescriptor<MessageDescriptorProto> {}
public partial class FileDescriptor : IDescriptor<FileDescriptorProto> {}
etc. Putting all of those into their own files would have been slightly silly.
One thing to bear in mind with all of this: using ReSharper makes it easier to get to your classes whether they're in sensibly named files or not. That's not to say that organising them properly isn't a good thing anyway; it's more to reinforce the notion that ReSharper rocks :)

I personally believe that every class should be in its own file, this includes nested types as well. About the only exceptions to this rule for me are custom delegates.
Most answers have excluded private classes from this rule but I think those should be in their own file as well. Here is a pattern that I currently use for nested types:
Foo.cs: // Contains only Foo implementation
public partial class Foo
{
// Foo implementation
}
Foo.Bar.cs: // Contains only Foo.Bar implementation
public partial class Foo
{
private class Bar
{
// Bar implementation
}
}

It depends. Most of the time I would say yes, put them in separate files. But if I had a private helper class that would only be used by one other class (like a Linked List's Node or Element) I wouldn't recommend separating them.

As someone who has been coding in large files for years (limited to 1,000 lines), in fact, since I started programming as a child, I was surprised at the huge consensus in this "one class per source file" rule.
The "one class per source file" is not without its problems. If you are working on a lot of things at once, you will have many files open. Sure, you could close files once you're finished with them, but what if you needed to re-open them? There is usually a delay every time I open a file.
I am now going to address points others have made and explain what I think are bad reasons for the "one class per source file" rule. A lot of the problems with multiple classes in one source file are resolved with modern source-editing technology.
"I hate having to scroll up and down" - Bad Reason - Modern IDEs now either have built-in functionality for getting quickly to the code you want or you can install extensions/plugins for that task. Visual Studio's Solution Explorer does this with its search function, but if that's not enough, buy VisualAssist. VisualAssist provides an outline of the items in your source file. No need to scroll, but double-click on what you want.
There is also code-folding. Too much code? Just collapse it into one line! Problem solved.
"Things are easier to find because they're identified by file" - Bad Reason - Again, modern IDEs make it easy to find what you're looking for. Just use Solution Explorer or buy VisualAssist!! The technology is out there, use it!!
"Easier to read/too much code" - Bad Reason - I am not blind. I can see. Again, with code-folding I can easily eliminate the clutter and collapse the code I don't need to see. This is not the Stone Age of programming.
"You will forget where the classes are in large projects" - Bad Reason - Easy solution: Solution Explorer in Visual Studio and the VisualAssist extension.
"You know what's in a project without opening anything" - Good Reason - no dispute with that one.
Source Control/Merging - Good Reason - This is actually one good argument in favour of the "one class per source file" rule, especially in team projects. If multiple people are working on the same project. It allows people to see what has changed, at a glance. I can also see how it can complicate merging processes if you use large, multiple-class files.
Source control and merging processes are really the only compelling reason IMO that the "one class per source file" rule should apply. If I'm working on my own individual projects, no, it's not so important.

They should be in different files, even when it seems like overkill. It's a mistake I still frequently make.
There always comes a time when you you've added enough code to a class that it deserves it's own file. If you decide to create a new file for it at that point then you lose your commit history, which always bites you when you lest want it too.

Public classes: yes
Private classes: (needless to say) no

I actually prefer pretty big .cs files, 5000 lines is pretty reasonable IMO, although most of my files at the moment are only about 500-1000 (In C++, however, I've had some scary files), however, . The Object Browser/Class View, Go to Definition, and incremental search (-I; Thanks for that tip, Jeff Atwood!), all make finding any specific class or method pretty easy.
This is probably all because I am terrible about closing unneded tabs.
This is of course highly dependant on how you work, but there are more than enough tools to not need to use horrible old '70s based file source navigation (Joking, if it wasn't obvious).

Of course! Why wouldn't you? Other than private classes it is silly to have multiple classes in a single file.

I think the one-class-per-file approach makes sense. Certainly for different classes, but especially for base and derived classes, whose interactions and dependencies are often non-obvious and error-prone. Separate files makes it straightforward to view/edit base and derived classes side-by-side and scroll independently.
In the days of printed source code listings running to many hundreds of pages (think of a phone book), the "three finger rule" was good a working limit on complexity: if you needed more than three fingers (or paper clips or post-its) as placeholders to understand a module, that module's dependency set was probably too complex. Given that almost no one uses printed source code listings anymore, I'll suggest that this should be updated as the "three window rule" - if you have to open more than three additional windows to understand code displayed in another window, this code probably should be refactored.
A class hierarchy of more than four levels is a code smell, which is in evidence if you need more than four open windows to see the totality of its behavior. Keeping each class in its own file will improve understandability for depth less than four and will give an indirect warning otherwise.

Related

Arranging solution files

My C# .NET solution files are a mess and I am trying to find a way of getting things in order.
I tried to put all close files together in the same folder I am creating for that purpose. For example, I put interfaces, abstract classes, and all their inherited classes at the same folder. By the way - when I do that, I need to write a "using" statement pointing to that folder so I can use those classes in other files (also a mess I guess).
Is there an elegant way of doing things more clean, and not a list of files that I find very confusing?
Is it a good idea to (let's say) open a abstract class file and add nested classes for all the classes derived from it?
Is there a way of telling the solution to automatically set the folder "using" statements above every class I create?
The best way is when your solution file system structure reflects your program architecture and not your code architecture.
For example: if you define an abstract class and after have entities that implement it: put them into the same "basket" (solution folder) if they make a part of the same software architectual unit.
In this case one by looking on your solution tree can see what is your architecture about (more or less) from very top view.
There are different ways to enforce the architecture vision, understanding and felling of the code file system. For example if you use some known frameworks, like NHibernate, or (say) ASP.NET MVC tend to call the things in the name the technolgy calls them, in this way one who is familiar with that technology can easily find itself in your architecture.
For example WPF force you define in code things in some way, but also you need to define byb the way Model, ModelView, View.. which you will do intuitively in seprate files. The technology enforcce you to define your file system in way it was thought.
By the way the topic you're asking for, is broad known dilema/question, not resolved, cuase the code is just characters sequence and nothing else.
Good luck.
It sounds like you're hitting the point where you actually need to break things up a bit, but you're resisting this because more files seems like more complexity. That's true to a point. But there's also a point where files just become big and unmanageable, which is where you might end up if you try to do nested classes.
Keeping code in different namespaces is actually a good thing--that's the "issue" you're running into with the folders and having to add using statements at the top of your files. Namespacing allows you to logically divide your code, and even occasionally reuse a class name, without stepping on other parts of your code base.
What version of Visual Studio are you using? One little known feature of Visual Studio is that it can automatically create the using directive when you type a class name. That would eliminate one pain point.
If I was in your shoes, I'd start looking for logical places to segment my code into different projects. You can definitely go overboard here as well, but it's pretty common to have:
A "core" project that contains your business logic and business objects.
UI projects for the different user interfaces you build, such as a website or Windows Forms app.
A datalayer project that handles all interactions with the database. Your business logic talks to the datalayer instead of directly to the database, which makes it easier to make changes to your database setup down the road.
As your code base grows, a tool like ReSharper starts to become really important. I work on a code base that has ~1 million lines and 10 or so projects in the solution, and I couldn't live without ReSharper's go-to-file navigation feature. It lets you hit a keyboard shortcut and start typing a file name and just jump to it when it finds a match. It's sort of like using Google to find information instead of trying to bookmark every interesting link you come across. Once I made this mental shift, navigating through the code base became so much easier.
Try using multiple projects in the same solution to bring order. Seperate projects for web, entity, data access, setup, testing, etc.
IF the files are in the same namespace you won't need a using statement. If you're breaking your code into multiple projects you'll need to reference the other projects with using statements.
Its up to you. Break things apart logically. Use subfolders where you deem necessary.
Not sure.
Yes, but you'll need to create a template. Search for tuturorials on that.
1) Your solution folders should match your namespace structure. Visual Studio is set up to work this way and will automatically create a matching namespace. Yes, this requires a using for stuff in the folders but that's what it's for.
So yes, group common stuff together under an appropriate namespace.
2) Yes, subclasses should probably live in the same namespace/folder as their abstract base, or a sub folder of it. I'm not sure if you mean all in the same file? If so I would say generally not unless they're very very simple. Different files, same folder.
3) Not that I'm aware of. If you right click the classname when you use it you can get Studio to automatically resolve it and add a using (Ctrl + . also does this)

Coding style with generics and inheritance [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to name C# source files for generic classes
We are currently re-evaluating how we do generic classes when we inherit from a general class. Currently we will put the following two class definitions in the same file
class Foo
{
// code for class
}
class Foo<T> : foo
{
// code for class
}
My question is a simple one, should we keep them in the same file, or split them into separate files?
So far the pros to keeping them in the same file is that you have all the code there right infront of you. The con is that when both classes get sufficiently large, it could become un-readable.
What I would like is good reasons as to why we should do one or the other. If you recommend separate file, I would also like you to include possible naming conventions, or a strategy to get around the fact that we can have only one file named Foo
This is a matter of opinion, but I'd keep them in the same file rather than try to maintain some naming convention for one or the other.
While I subscribe to one class, one file, I think there is value in having these together. We really treat these as one class, right? Typically, Foo will be abstract, and is just a way of using our generic types… well, more generically -- in places where the type parameters don't matter and can't be known at compile time.
If the classes become too large, it should be a red flag anyway that some responsibilities should be broken out.
Unless classes are utterly trivial, I never put more than one in a single file. It's much easier, IMO, to find exactly the class you seek when you have a predictable, unique file name, with namespaces based on folders, generally.
For naming your files, maybe this:
foo.cs
foo_t.cs
foo_tuv.cs // for a foo class with three generics
I'd recommend keeping the classes in the same file. It makes it easier to locate all Foo classes. Also, with code folding (regions) you can easily view only a single class by collapsing the other.
That said, I wouldn't say either way is wrong. In the end this is one of those things that will take some experience to come up with your personal preference and find what works for you in your particular project. And you may find that what works well for one project doesn't necessarily work for your next project.
Answered here:
I think the common solution to this problem is to name the file like
this:
{ClassName}`{NumberOfGenericParameters}
This would give you this filename:
Bag.cs and Bag`1.cs
This is the way Microsoft handle this issue in frameworks like Asp.net
Mvc.
Keep these classes small and you can keep them in one file. If you can't keep them small, divide them. If you prefer keeping them in separate files, it's okay too. But keep them small anyway. In case of separate file, I would use FooGeneric name but someone here How to name C# source files for generic classes recommends Foo`1 (for 1 parameter).

How to organise large code files?

I am increasingly aware that my code in any single file can often span hundreds of lines quite easily and although I know the implementation might be sound, it still feels messy and unorganised.
I understand that there are situations where a lot of code is neccessary, but whats the best way to organise it all?
I've thought about separating variables from methods, privates from publics and internals but I don't want to because I can't help thinking that the components of ONE class belong in ONE file.
This whole thing is compounded when I'm working with the codebehind of a WPF window, which always seem to grow at an exponential rate into one huge mess very quickly.
Also: C# has a keyword called partial, which allows you to split a class over any number of files without affecting the functionality. However, I have noticed that Microsoft only seem to use partial to hide generated code from you (Winforms / WPF.) Which leads me to question whether splitting a class simply because it has many lines is a legitimate use of partial - is it?
Thanks
Separate your code into responsibilities. For each responsibility, define a single type. That is, follow the Single Responsibility Principal. Doing so will result in smaller units of code, each of which performs a very specific function. Not only does this result in smaller files, but also in better design and maintainability.
If your files are big because they contain a single class/struct that is big, then this is usually (but not always) a hint that your class is dealing with multiple concerns and can be refactored into a number of smaller, more specialised classes.
If I understand you, your main problem is that your forms end up being too big, which leads to the classes for those forms containing too much code, which is quite normal if your forms aren't very simple. The way to try minimize this is by using User Controls since if you move the controls to other classes, you also move the code behind to other classes.
It can sometimes make it a little more difficult to communicate between the controls, but that's usually more than made up for by the fact that the code in each class will be much easier to understand.
I tend to group properties, constructors, methods, and helper methods (private methods) together with regions. If I have a lot of methods, I create more regions based on what they do (especially good for overloads). And speaking of overloads, try minimizing your code with optional parameters.
As far as I understand partial means that the class exists in two separate files. Webforms and controls are partial because the other "part" of the file is the as[p|c]x file that goes with it.
I go on the theory that if you cant see an entire method on one screen (i.e. you have to scroll), you should break the method up into further methods - either in the same class or when the code will get used more than once into a helper class.
We use stylecop. It helps a bit because it enforces a structure on your code and an order for what should appear where. Hence you can then find your way around larger files a bit more intuitively.
To improve code readability: you can use the region block: https://msdn.microsoft.com/en-us/library/9a1ybwek.aspx . As for improving the structure and design of your code - consult some specialist books.

How to change a file which is too large (got warning from StyleCop)?

I am recieving warning about my file by StyleCop.
Warning 1 CR0005: The file is very long at 508 lines. Please consider refactoring to make it 500 or fewer lines.
Warning 2 CR0002: Method is too long. It is 58 lines long. Consider refactoring to make it 50 or fewer lines.
How are you guys making changes to your codes? What are the best practices for this? I have no idea to divide my codes to smaller ones - being afraid of making my codes become so-complex.
So, please help ^_^ !
Nam.
You should read Martin's Fowler book "Refactoring: Improving the Design of Existing Code" and "Professional Refactoring in C# & ASP.NET" of Danijel Arsenovski.
Does the class try do to much? Could it be split into multiple smaller classes that each had a more specific and better defined purposes? If so, refactor it into multiple classes.
Could some code from the method be extracted out into it's own method to make it easier to understand? If so, do so.
Would either of the changes above make the code more difficult to understand? If so, ignore StyleCop. Remember, it's just a generic tool to help make your code easier to read. There will almost certainly be at least some recommendations that won't make sense for your circumstances.
I'd suppress the warnings and worry about more important things.
I'm not sure it makes sense to impose such an arbitrary limit on the size of a file or method. It's not so much the numbers 50 & 500 themselves, but the fact that there is such a number. Where does it come from? Why is 50 lines considered readable, but 58 isn't?
As demonstrated here, concentrating on these metrics can be counter productive, and draw attention away from real issues. Perhaps time might be better spent, and good design principles better served, ensuring something like proper separation of concerns, for example. Split your lines and methods according to what should logically go in them, rather than breaking them up to meet arbitrary size criteria.
Well, the 'Extract Method' refactoring is very useful for making methods shorter (by putting them into another method), which I believe is in 2010. (Highlight some code, right click and it should be in the menu somewhere).
The best way to break a file up (assuming you only have one class in it) is to extract some of the functionality into another class. Google 'Extract Class' and you'll find some info on it.
Like #Justin says, doing this might seem more complex at first because there are more files/methods to deal with, but because each file/method is smaller, there's less to deal with at any one time. Some (respected) people take this really far. It takes a little getting used to but you code will be (arguably) better for it.
Others have mentioned refactoring, and also focusing on breaking the class down to do just 1x responsibility (part of the S.O.L.I.D. rules for OOP). However; if your class is still 500x lines, and performing one responsibility, then you're not in too terrible a position.
If your code-file contains XML documentation and white-spaces, then 500x lines is only slightly large (and that's dependent on what it does). Many of my "simple" classes end up around 350 lines once completed. Smaller is better, but concise is really what you want.
Another good book for understanding how your code should look is Robert C. Martin's Clean Code. It lays down many good rules in designing well thought-out classes and methods.
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. For example here the 'bar' class is split between foo1.cs and foo2.cs.
foo1.cs
public partial class Bar
{
public void bat()
{
}
}
foo2.cs
public partial class Bar
{
public void baz()
{
}
}
For more information on this see Partial Class Definitions (C# Programming Guide)
This is not a rule that ships with StyleCop. Is it something your company developed in house? I'm curious about the rationale behind the rule. 500 lines seems like a pretty strict limitation.

Are C#'s partial classes bad design? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm wondering why the 'partial class' concept even exists in C#/VB.NET. I'm working on an application and we are reading a (actually very good) book relavant to the development platform we are implementing at work. In the book, the author provides a large code base/wrapper around the platform API and explains how he developed it as he teaches different topics about the platform development.
Anyway, long story short - he uses partial classes, all over the place, as a way to fake multiple inheritance in C# (IMO). Why he didn't just split the classes up into multiple ones and use composition is beyond me. He will have 3 'partial class' files to make up his base class, each w/ 3-500 lines of code... And does this several times in his API.
Do you find this justifiable? If it were me, I'd have followed the S.R.P. and created multiple classes to handle different required behaviors, then created a base class that has instances of these classes as members (e.g. composition). Why did MS even put partial class into the framework? They removed the ability to expand/collapse all code at each scope level in C# (this was allowed in C++) because it was obviously just allowing bad habits - partial class is, IMO, the same thing. I guess my question is: Can you explain to me when there would be a legitimate reason ever to use a partial class?
EDIT: I'm aware that for Web/WinForms there is no other choice. But outside of this? Why didn't MS just put some different keyword for gluing code-genn'ed classes together? Or is there really a legit design scenario that merits it?
I do not mean this to be a rant / war thread. I'm honestly looking to learn something here. When should partial classes be used in code design? Simple question, no need to close
Thanks
Can you explain to me when there would be a legitimate reason to ever use a partial class?
One of the most legitimate and useful reasons is to encourage the separation of automatically generated code and your own custom extensions to it. For instance, it's common to have an automatically generated form code from some kind of designer, but you usually want to add your own specific behavior to it. This way, if you regenerate the automatic-code portion, you're not touching the part that has your specific extensions.
That said, it's quite possible to have too much of a good thing. Some tips:
Don't make your classes partial for the sake of being partial.
Don't put partial classes anywhere except besides one another. If you have to jump to a completely unrelated section of the project to see the other half of the class, you're probably doing it wrong.
Don't use partial as a technique to obscure the size of the class. If you're breaking up your classes with partial because they're too big, you should revisit the Single Responsibility Principle.
If you have three or more partial fragments for the same class, it's almost a guarantee that you're abusing partial. Two is the typical upper bound of reasonableness, and it's generally used to segment automatically-generated code from handwritten code.
Anyway, long story short - he uses partial classes, all over the place, as a way to fake multiple inheritance in C# (IMO). Why he didnt just split the classes up into multiple ones and use composition is beyond me. He will have 3 'partial class' files to make up his base class, each w/ 3-500 lines of code... And does this several times in his API.
Yes, that's definitely a clear abuse of partial!
There are two reasons that I would (and do) use partial classes.
To separate auto-generated portions of the code (such as WinForms designer code or T4 output).
To allow nested types their own file while still achieving the encapsulation required by your design.
Update
I can see that some are not convinced about my second point, so let me give an example; the ListViewItemCollection in the framework. It is quite rightly nested under ListView because it is only for use by ListView, but to make maintenance much easier, I would give it it's own file by using partial classes. I don't see this as bad design or a misuse of the partial keyword.
For more discussion, check out the question that this one duplicates: Partial Classes in C#
Another legitimate use of partial classes is to help reduce the "monolithic web service" clutter in WCF. You want to to break it down into logical groups of functionality but don't want to have to create a ream of individual service instances/endpoints (presumably because they share state, resources, and so on).
The solution? Have the service implement multiple interfaces, and implement each interface in its own partial class. Then map different endpoints in the configuration to the same physical implementation. It makes the project a lot more maintainable, but you still only have one physical endpoint.
In some cases I'd point to this type of approach as a poor practice on account of the SRP, but when you're working with WCF services or web services in general, it's not quite so simple. You have to balance internal design requirements against external consumption requirements.
One less common use might be to split up a huge class into separate physical files to make life easier from a source control point of view. I've just joined a project containing some enormously bloated web service classes running to thousands of lines of code and with methods related to several different business functions.
Merging from various feature branches is a nightmare due to different teams making simultaneous unrelated changes in the same file. I can't split the web service up without making some seriously breaking changes, but breaking the class up into partial classes preserves the behaviour exactly, and removes a whole bunch of merging issues.
I'm definitely not encouraging the above as a design choice, but it was a nice quick win for us, and goes to show that partials aren't evil all the time...
I've used partial classes in many different ways in the past. As I learn more about programming and in particular the concept of "favor composition over inheritance" I can easily see the need diminishing for both vertical inheritance and overuse of partial classes.
Other than auto-generated code, I cannot think of good use of partial classes. Even if you use EF, and need different metadata, they don't even recommend using partials for metadata. In fact if you try to duplicate any properties in another partial(just to add metadata) you'll get a compiler error.
The more we learn about refactoring and SOC (Separation of Concerns) the smaller and more focused our classes become. They are by default, re-used, which over time makes them bullet-proof and easily tested. Just say NO to gargantuan programs. Henry Ford learned this concept in the early 1900's programmers started learning it 100 years later.
Use composition when you can...
I fully agree with John's answer. But I would take it one step further.
Don't make your classes partial.
The only use of partial classes I can think of that I would consider "good design" is with automatically generated code. Any other use is almost certainly unnecessarily splitting up your class. (Actually, I can see that Jeff's second point on nested classes is possibly a valid use)
Personally I think this book you are reading sounds like bad design, however do consider that he may just be using partial classes so he can just demo part of the code little bits at a time rather than just presenting the whole class in one go.
Can you explain to me when there would be a legitimate reason to ever use a partial class?
Recent versions of Visual Studio use partial classes to seperate the auto-generated designer code from your own code..
An ASP.NET example:
Page.aspx
Page.aspx.cs <- Your code
Page.aspx.Designer.cs <- A partial class containing auto generated code.
A WinForms example:
Form1.resx
Form1.cs <- Your code
Form1.Designer.cs <- A partial class containing auto generated code
I've used partial classes to "physically" separate static data access methods from business class properties and methods in an active record architecture. For example, we had Company and CompanyData partial classes side-by-side. The advantage was that one file was the POCO and the other contained only data access methods. This was a stepping stone to removing data access to repository classes in a legacy application. I think that was a legitimate use, it certainly made the re-factoring process saner.
Another good use for partial classes would be when implementing the Abstract factory pattern. Make the root factory object partial and then place the actual factory methods in the same file as the class the factory instantiates.
EDIT: Partial classes also work well for classes that interact with a configuration file. Place the code containing the configuration parameters near the code that actually uses the configuration parameter.
Just stumbled across this thread while googling the benefits of partial class.
I am in the process of converting a Java EE application into a silverlight based .NET one.
I came across the following code in the view layer :
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
...
public partial class Wwcusts04d : System.Windows.Controls.Page {
Now, if the partial page itself is autogenerated, what's the use of maintaining it ?
Also, the code inside just links various controls to their names. I don't confess to have knowledge of silverlight, but isnt this thing better suited in xaml?
Partial class exists in the .Net framework solely to let Visual Studio designers (e.g. the Asp.Net designer and the Windows Forms designer) to generate code / mess with your classes while keeping that generated code in a separate file.
(See .NET Partial Classes vs. Inheritance)
If you do something similar (generate code that needs to coexist with user-written code) then you might also find partial classes useful, but I don't believe that Microsoft ever intended partial classes as a language concept to be useful to anyone other than the Visual Studio team.
Its not so much that using Partial classes is bad design - its just you probably wont find a use for them.
I've used a partial class twice in VB.Net, and both times were for the rare occasion that I needed late binding. Simply create a partial class and turn Option Strict Off at the top.
Just to add on to the previous answers that mentioned separating generated code from custom code, I've found partial classes useful for extending strongly-typed datasets.
There's a lot of discussion out there on this topic, and lots of people saying that 1) it's bad design to use partial classes, 2) that it's used for autogenerated code, and 3) that it shouldn't take the place of inheritance.
I have a situation, though, in which partial classes look like they'll come in very handy: I'm building a series of applications which will eventually be integrated into a suite. They'll all have a main form which will provide some functionality, and several shared components (e.g., a form to display reports). While I could define a base class and inherit from it, that would mean a lot of rework when the time comes to combine all of the applications into the "enterprise" version of the product.
Thus, partial classes are quite useful, because I can quite simply include the various partial classes into the combined version, while still allowing me to build the individual, stand-alone versions of the product. If I were to try to accomplish this using inheritance, I'd end up with each component calling its own version of the common components (e.g., InvoiceReportViewer, PurchasingReportsViewer, etc.) rather than simply calling ReportsViewer and knowing that Visual Studio will have integrated all of the bits for me.
Another thing to consider, partial classes forces you to create different file names which contains same class name. For example you have FactoryClass and you are creating partial versions of it like; Factory.designer.cs, Factory.data.cs and all those files has class named FactoryClass.
If you navigate to this question; there is a best practice defined as:
Best practice, however, is to define one class per file and to give the file the same name as the class (or struct, etc.) being defined.

Categories

Resources