Miguel Posada
Miguel Posada

Reputation: 33

Sharing code in C# between projects without making classes public

I have a C# library with lots of internal functionality exposing only a few public classes and interfaces. I would like to share this code between several projects, and each project may need to extend the internal classes with subclasses.

I don't like the idea of making all these classes public in order to create a common library. I think it exposes them too much to easy decompilation and break the design.

Is the only real option to create a copy of the source code and keep those files in sync between projects? Or is there some way I can share code and still get a single library for each project exposing only the few intended public interfaces and classes?

I'm using Visual Studio 2010.

UPDATE

Thanks for the clarification regarding decompilation and "private" access. I think I could consider applying an obfuscator over several input libraries, all together, hopefully obfuscating even their public connections.

From the design standpoint, seems like the answer is definitively to use friend assemblies.

Upvotes: 3

Views: 3141

Answers (5)

Joel Coehoorn
Joel Coehoorn

Reputation: 416179

I think it exposes them too much to easy decompilation

You're in for a shock then, as even private classes in an assembly can be trivially de-compiled and used to create a public implementation.

"Breaks the design" is another issue. If you want to use this code from separate projects, than making them public is exactly the right thing to do. If you do not want to make them public, than think about what interface this project really wants to expose to the outside that will still accomplish what you need... and build that api and make it public.

Upvotes: 0

Justin Pihony
Justin Pihony

Reputation: 67125

You can accomplish this using the InternalsVisibleToAttribute on your assembly

Upvotes: 2

Sam Axe
Sam Axe

Reputation: 33738

Create a new project. File > Add > Existing. Select the existing code files. Hit the drop down on the Open button and choose Link.

making classes internal vs public has absolutly zero bearing on its ability to be decompiled.

Upvotes: 3

Steve
Steve

Reputation: 31662

You are looking for "friend" assemblies: http://msdn.microsoft.com/en-us/library/0tke9fxk(v=vs.80).aspx

Upvotes: 2

Joshua Enfield
Joshua Enfield

Reputation: 18318

You may want to look at doing friend assemblies:

http://msdn.microsoft.com/en-us/library/0tke9fxk(v=vs.80).aspx

[assembly:InternalsVisibleTo("someassembly")]

Upvotes: 8

Related Questions