Reputation: 77389
I have a static class in a shared project, which I want to extend with further methods in another project. Because the method I want to extend the static class with is only applicable to the 2nd project and also dependent on other classes in that different project, I can't just move it to the shared project.
Basically I have class X in MySolution.SharedProject. I want to create a method X.Get() in MySolution.PrimaryProject which references SharedProject.
It seems that I can't do partial across projects, and I also can't extend static classes using extension methods.
How do I do this??!
For all later visitors: The chosen answer does what I asked, but the BETTER way is what Jon Skeet outlined - choose different class names and get it over with.
Upvotes: 6
Views: 10062
Reputation: 48516
You can't use partial classes. You could use inheritance, but then you're not allowed to make the class static
, so just make all it's methods static. Then prevent instantiation by making it's constructor protected:
namespace SharedProject
{
public class X
{
protected X() { }
public static void SharedMethod() { }
}
}
namespace PrimaryProject
{
public class X : SharedProject.X
{
protected X() { }
public static void ProjectMethod() { }
}
}
You'll be able to see both methods when using PrimaryProject.X
. Naturally these classes would actually be in different files, and indeed, in different projects.
As Jon pointed out, this can get a little confusing however. Personally I would just use two different class names and no inheritance.
I know, it's a little annoying to come up with names every time, and identifical class names in different namespaces are also somewhat unpractical. If your namespaces are very long, aliasing them locally with the using
directive can be of help.
Upvotes: 5
Reputation: 1504122
You can't. A type can only exist in a single assembly. (That's why partial types can't be split between projects. The CLR has no concept of partial types - they're just compiler magic to compile a single type from multiple files.)
Why not just create a new type in the second project? Where would the benefit be in "extending" the class?
EDIT: It certainly sounds like you should have two classes, e.g. CommonValidation
and ProjectValidation
. It should be obvious which methods belong in which class... I really can't see why it would create a problem.
Upvotes: 17
Reputation: 1064274
but the configuration object is not available in the shared project, only in the primary one
So those methods should only be visible in the primary project, but I still want to re-use the rest as part of my shared library.
It sounds like you simply want some of the methods to be internal
?
public static class Foo
{
public static void AvailableAnywhere() {...}
internal static void AvailableForThisAssemblyOnly() {...}
}
If I've misunderstood, then other options include:
[InternalsVisibleTo]
Upvotes: 2