Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulating partial classes across assemblies

Tags:

c#

.net

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?

like image 304
Herman Schoenfeld Avatar asked Oct 21 '25 16:10

Herman Schoenfeld


1 Answers

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.

like image 74
Dai Avatar answered Oct 24 '25 07:10

Dai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!