Reputation: 8734
I'm trying to group together MANY helper classes into a common parent class for ease of use. For example, in my applications I want to do
Tools.StringTool.foo(..)
Tools.NumberTool.bar(..)
Tools.NetworkTool.something(...)
The idea here is to organize all the tools under a common Tools class so that intellisense can bring them all up when I type "Tools.".
Defining all the tools under a parent static partial class Tools works fine but not for Tools in a different assembly.
I tried to emulate static partial classes across assemblies by replacing the parent Tools class with a namespace X.Y.Tools, but for code written outside X.Y namespace, I need to fully qualify each tool before using it.
i.e. in app code
Tools.MyTool(..) // won't compile
X.Y.Tools.MyTool(...) // will compile but ugly
Any suggestions how I can solve this issue or alternative approaches for organizing the tools?
Upvotes: 4
Views: 2366
Reputation: 8734
Turns out the easiest way to do this is simply use namespaces
// in project 1
namespace Tools {
public static class NetworkTool {
}
}
// in project 2
namespace Tools {
public static class FileTool {
}
}
// in client code (references both projects)
Tools.NetworkTool.SomeMethod();
Tools.FileTool.SomeMethod()
Upvotes: 2
Reputation: 155648
You can use extension methods in this case. All extension methods defined in classes within a namespace are made available when that namespace is imported.
This way you'd have static classes like MyUtilityNamespace.MyClassInAssembly1
and MyUtilityNamespace.MyClassInAssembly2
that all provide extension methods onto a single class instance, but this has ugliness associated with getting that class instance, like so:
// in central assembly
class Tool {
private static Tool _t = new Tool();
public static Tool T { get { return _t; } }
}
// in utility assembly 1
public static class MyExtensionClassInAssembly1 {
public static void SomeUtilityMethodX(this Tool tool, Object arg1, Object arg2) {
// do something
}
}
// in utility assembly 2
public static class MyExtensionClassInAssembly2 {
public static void SomeUtilityMethodY(this Tool tool) {
// do something
}
}
You'd use it like so:
Tool.T.SomeUtilityMethodX( Tool.T.SomeUtilityMethodY(), null );
it isn't pretty, but means you only need to import an namespace once, and the Tool.T
is constant, there's no need to memorize StringTool
or NetworkTool
.
Another alternative is to use namespace or type aliasing, however this is laborious as you need to specify the using Tools = X.Y.Tools.MyTool;
line on every source file you have.
Upvotes: 3