Partial classes in separate projects - c#

I have a question the answer i cant find for.
I have solution with Module projects. There are the same class types in each. My purpose is to make them all partial and define partial method.
I tried to use the same namespace and the same Project namespace, but it doesnt work. Can somebody give me an advice how to do that?
Thanks so much.
Upd. any workaround (in there is no straight way) will be appreciated

Partial classes are compiler magic. In other words no matter you have partial class, while compiling compiler will combine all partial classes into single unit.
Since this all happens separately for each assembly it is not possible.
Very close workaround which I can see is Inheritance.

Unfortunately, you cannot have a partial class span multiple projects. Partial classes are only combined within individual projects/assemblies.
See this StackOverflow post for more information and some possible workarounds (e.g. inheritance and extension methods).

It will not work out of the box because it would mean that the same class will live in two separate assemblies (metafiles).
Workaround: you can try to merge one project into another on Pre-Build event

Related

What are the pros and cons of making a FAT class a partial one & splitting it into partial classes?

Recently I was considering a class that seems to become fat because of too many methods in it.
A legacy code...
That has many business logic-wise methods doing all types of CRUD on various 'Etntities'.
I was thinking
make this class partial
and then grouping all methods by their target entities they work on
and splitting them into separate physical files that will be part of the partial class
Question:
Can you list pros and cons of such a refactoring, that is making a fat concrete class a partial class and splitting it into slimmer partial classes?
One pro I can think of is the reduction of conflicts/merges in your source control. You'll reduce the number of parallel check-outs and the merging headaches that invariably come when the devs check-in their work. A big pro, I think, if you have a number of devs working on the same class quite often.
I think that you are talking only about simplicity to handle the class. Performance or behaving pros and cons shouldn't be because when compiled it should generate the same result:
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.
Now answering pros and cons I can think in (only about simplicity):
Pro: less conflicts / merges if working in a team.
Pro: easier to search code in the class.
Con: You need to know which files handles each code or it can get a little annoying.
I would go for the refactor. Specially considering all facilities given by the IDE where you just have to click F12 (or any other key) to go to a method, instead of opening the file.
Splitting a large class into partial classes perhaps makes life easier in the short term, but it's not really an appropriate solution to the code bloat that your class is experiencing.
From my experience, the only benefit that splitting an existing large class up gives you is that it's easier to avoid having to constantly merge code when working with other developers on said class. However, you still have the core problem of unrelated functionality being packaged into one class.
It's better to treat the breaking down to partial classes as the the very first step in a full refactoring. If you're able to easily extract related methods and members into their own partial classes (without breaking things) then you can use this as the basis for creating entirely standalone classes and rethinking the relationship between them.
Edit: I should clarify that this advice is given under the assumption that your legacy code has unrelated functionality in one class as a result of years of "just add one more method here". There are genuine reasons for having functionality spread across partial classes, for example, I've worked on code before that has a very large interface in one file, but then has all the methods grouped into partial classes based on areas of product functionality - which I think is fine.
I would say Partial class would help to maintain the code and will be more helpful when we have legacy code to avoid more changes on the reference side. Later will help to refactor easily
If you're concerned about how to refactor a class, I suggest reading into SOLID design principles.
I think you should focus on Single responsibility principle (the S in SOLID), which states an object should only have one responsibility.
I think my answer is not directly answering your question whether using partial classes would be beneficial to you, but I believe if you focus on the SOLID design principles that should at least give you some ideas on how to organize your code.
I see partial classes only as a way of extended a class that's code was generated (and can be re-generated at any time) that you would like to extend without your custom code being overwritten. You see this with the Form generated code and Entity Framework DbContext generated code for example.
Refactoring a large legacy class should probably be done by grouping and separating out single responsibilities into separate classes.

Inheritance in Specflow features

I am looking for a way to implement inheritance in specflow features. For e.g a base features class which has common scenarios which have to be tested.
3-4 derived features classes which inhert all the scenarios in the base class and add some of their own. Similarly the Binding class will also follow a inheritance structure. This is needed to test an ASP.NET MVC application which has a base controller (scenarios in base features class) and 4-5 implementations.
I can copy the features file for each derived controller class but this would lead to considerable duplication.
Is this possible in specflow, Or am I going down the wrong route? Please help. thanks,
I'm not 100% sure if this is the right path to take (read as, I've never needed to do anything like this). For me any inheritance and re-use comes in the Step Definitions (or Binding) classes. But even so...
I don't know if you can simply do this using the tools available in SpecFlow - but you have the following option so far as I can see (this isn't a tested theory... I might test it later - but I figured this might offer you an idea...)
The "code-behind" (designer-generate-code) for your Feature files are partial class implementations...
...so I guess you could create a "base" (generic) Feature file...
...then create a partial class file for each of your specific/implementation Feature files' code-behinds...
...each partial class will specify a base class which is the generated class name from the "base" Feature file code-behind.
Hopefully this helps a little.
EDIT:
Okay I've tested this theory... It would work as I've described above. I just created a new project with associated test/spec project, and did the above in the test/spec project. The test runner ran the base feature, and then ran the specific/implementation feature... which included the base feature again.
Have a go - it takes less than 5 minutes to knock up what I've suggested, and see if the result fits your requirement.

Refactoring to Partial Classes - Guidance

I am dealing with a huge codebehind of a an ASP.NET user control. I am taking the approach of refactoring the huge class into a number of partial clasees separted by UI intent.
Is there guidance on:
Number of partial classes I am must constrain myself to.
Naming or names to be given toof the partial class files.
There's no limit to the number of Partial Class files you can use. They all compile into a single class at compile time. The more partial class files, though, the more confusing things could be when trying to find different functionality in the class.
I would name the files starting with the class name and then follow up with which concern the file was addressing. That way you're a little more clear about what is in each file.
You should also be careful about your class. If a single class is addressing several different UI Concerns to the point that you feel it should be separated into separate files it sounds like your class should be broken up into several smaller, more concise classes (rather than a single monolithic class defined across several files).
I'm not familiar with a partial classes limitation.
About file naming, again - no limitation. It could be anything.
My personal preference would be [MainClassName].[aspect].cs,
for example: MyHugeControl.Reports.cs, MyHugeControl.Data.cs, etc.

C# namespace visiblity

My situation is very simple.
I have a class A, called through WCF service, which delegates it works to several 'helper' classes. These 'helper' classes are obviously internal. The problem is that I don't want that someone may call these classes directly. I would like that they always call the class A. This means that I need a 'namespace visibility'. I think that I can simulate it by making the 'helper' classes private (so I will include them in A, which will be split, thanks to the partial keyword, into several files (one per helper class)). What is your opinion on that solution ? Is it very dirty ?
Thanks in advance.
If the helper classes are internal, code outside the assembly won't be able to call into them anyway. Do you really not trust the rest of the code in your assembly?
There's no such thing as namespace visibility in .NET, although I agree sometimes it would be useful.
I would say that using partial to effectively make one giant class would be a pretty ugly solution. I'd just leave it at internal visibility and use normal code review processes to avoid calling into the helpers from elsewhere. Heck, you may even find that the helpers are genuinely useful elsewhere (or at least some bits of them).
Yes it would be a ugly solution. The practical way would be to only include class A and other helper classes in a separate assembly with A being public and the helper classes being internal. Do you really have a legitimate concern that other classes in the same assembly should not be able to use the helper classes. Generally an assembly is a structural unit and created by one team.
Another option (if you want to resuse the helper classes) is to put all internal helper classes in one assembly and then use the InternalsVisibleToAttribute to open this classes for use from e.g. AssemblyA that has class A.
For smaller solutions, you should be OK with splitting your assembly when you need the encapsulation.
But for very large solutions (>100 projects), you might be forced to find alternatives, as visual studio starts behaving badly once you pass 150 projects - build times soar and you start running out of memory.
This has sadly not improved very much in VS2010.

How are partial methods used in C# 3.0?

I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.
A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.
The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.
The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.
In .Net 1 it was auto-generated code in a #region block
In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer
This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.
In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.
The extra bit here is that code needed to provide methods that developers might want to fill in.
As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.
The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.
Empty methods are not optimised out.
So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.
So that it can do this partial methods always return void.
If you create a new Linq DBML file it will auto-generate a partial class, something like
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
partial void OnCreated();
partial void InsertMyTable(MyTable instance);
partial void UpdateMyTable(MyTable instance);
partial void DeleteMyTable(MyTable instance);
...
Then in your own partial file you can extend this:
public partial class MyDataContext
{
partial void OnCreated() {
//do something on data context creation
}
}
If you don't extend these methods they get optimised right out.
Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.
The example I mentioned before is one possibility:
//this code will get optimised out if no body is implemented
partial void DoSomethingIfCompFlag();
#if COMPILER_FLAG
//this code won't exist if the flag is off
partial void DoSomethingIfCompFlag() {
//your code
}
#endif
Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.
Partial methods are very similar in concept to the GoF Template Method behavioural pattern (Design Patterns, p325).
They allow the behaviour of an algorithm or operation to be defined in one place and implemented or changed elsewhere enabling extensibility and customisation. I've started to use partial methods in C# 3.0 instead of template methods because the I think the code is cleaner.
One nice feature is that unimplemented partial methods incur no runtime overhead as they're compiled away.
Code generation is one of main reasons they exist and one of the main reasons to use them.
EDIT: Even though that link is to information specific to Visual Basic, the same basic principles are relevant to C#.
I see them as lightweight events. You can have a reusable code file (usually autogenerated but not necessarily) and for each implementation, just handle the events you care about in your partial class. In fact, this is how it's used in LINQ to SQL (and why the language feature was invented).
Here is the best resource for partial classes in C#.NET 3.0: http://msdn.microsoft.com/en-us/library/wa80x488(VS.85).aspx
I try to avoid using partial classes (with the exception of partials created by Visual Studio for designer files; those are great). To me, it's more important to have all of the code for a class in one place. If your class is well designed and represents one thing (single responsibility principle), then all of the code for that one thing should be in one place.

Categories