Search code examples
c#visual-studioprojects-and-solutionssolutionproject-reference

How to use a C# class in many projects inside the same solution?


I'm learning C# and I don't know exactly how to make a class visible to all projects inside the Solution.

Basically I have many projects, all Windows Forms, all of them have some similarity, so they can share a lot of classes. I think a good approach is put all the shared classes in the Solution folder and make all the project (apps) get the classes from there.

Is this a good approach?

And how to do it?

Another way to do it, I think, is to put all the shared classes in one project (app) and let the other projects refer to that project.

Is there a better approach?

I'm using Visual Studio 2019 and this is what my Solution looks like that I haven't been able to share the classes between the projects:
enter image description here


Solution

  • Create a Class Library project within your solution and put your shared classes in there:

    • Right click on your solution in the Solution Explorer -> Click Add -> Click New Project... Add -> New Project...

    • Choose Class Library (and name the library something in the next step) Add a new Library

    Then in each of the projects that you want to access the classes from:

    • Right click on Dependencies -> Click Add Project Reference... Right click Dependencies

    • Tick the class library project you created enter image description here