Search code examples
c#code-reuse

Using a class in two projects


I have a class ProductKeyLib that is part of project MyProgram-Web, which itself is a part of solution MyProgram. As of now, this lib only checks whether the key is valid, but does not generate one. The interface for key generation will be in project MyProgram-KeyGen, which also is part of solution MyProgram.

Now, the tricky part: I would like to have both functions (generation and check) in one class, because, as you may guess, 100% compatibility between key generation and key check is better achieved when everything is in one file, and also my unit tests will be easier then.

But: both programs should include that part in their program, I don't want to have a special dll. Furthermore, MyProgram-Web should only include the checking part, not the key generation.

Can I do that in VisualStudio? If so, how?


Solution

  • Well, it's probably not a good idea, but you can use a combination of compiler defines and linked source files.

    So you'd have a single cs file containing all the code linked to both projects (no common library - just the single code file). In it, you'd have all your code:

    #if KeyGen
    public string GenerateKey(...)
    {
      ...
    }
    #endif
    
    public bool CheckKey(...)
    {
      ...
    }
    

    Then, in your keygen project, you'd put a compiler define named KeyGen, and the generation code will only be compiled in the keygen part, and not the client application.

    However, this still reeks of "security by obscurity". If the key generation and checking is actually important, this would be insufficient. For example, just through knowing how the key is checked, you can in many cases easily find ways to construct the keys (and even brute-force algorithms are very reliable nowadays, even without utilizing the GPU).