Search code examples
c#code-reuse

Reuse class / no references


Task: reuse C# code in different projects but without project referencing (don’t want extra dll/references just because of a small utility class). There’re 4 projects, one of them contains utility class which is currently source-code-linked by other 3 projects. Problem: once one of the projects starts referencing one of others (for some other needs), the compiler starts complaining (obviously) that there’s the same class (with the same namespace) in these projects.

Are there any solutions other than to move the class to separate project or to make 4 copies of the class for each project and maintain them separately?

I wonder is there a way to source link files so that the class inside a file gets project-specific unique namespace…


Solution

  • I wonder is there a way to source link files so that the class inside a file gets project-specific unique namespace…

    Well you could use preprocessor directives:

    #if PROJECT_FOO
    namespace Foo
    #elif PROJECT_BAR
    namespace Bar
    #elif PROJECT_BAZ
    namespace Baz
    #endif
    

    ... and then link the file into each project, defining appropriate symbols in the project properties.

    But I would thoroughly recommend against it. It's horrible, and it's certainly not how C# was designed to be written.

    Just break it out into a separate project - you're bound to find you want more and more code like this anyway.