1

I was wondering if two separate C# Windows projects (in two separate solutions) can share one .cs file with shared definitions? If so, then how?

PS. One project is ASP.NET web app and the second project is C# Windows service (started as a Windows console project.)

ahmd0
  • 16,633
  • 33
  • 137
  • 233

2 Answers2

6

Add Existing Item->Add As Link (found by selecting drop down on Add button)

chillitom
  • 24,888
  • 17
  • 83
  • 118
  • Do I define a `namespace` on it? – ahmd0 Apr 09 '13 at 16:39
  • It will use any namespace defined in the file if one exists otherwise I believe it will use the default namespace of each project. – chillitom Apr 09 '13 at 16:40
  • Thanks. I just tried it and it seems to work. Good idea. I've been using VS for all this time and I didn't see that "Add as link" button. – ahmd0 Apr 09 '13 at 16:44
  • There's only one funky issue with it. When I work with the shared .cs file in one project, if it's not saved there the other project won't see the changes. Normally VS intellisense is pretty good at not-caring about such things in the same project. – ahmd0 Apr 09 '13 at 16:54
2

Move that cs file/code to be shared to a new class library project and refer that in your other 2 projects.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Just curious, what is the benefit of moving that CS file to a `class library project` versus what @chillitom suggested? – ahmd0 Apr 09 '13 at 16:37
  • 1
    Sharing the code in a separate DLL ("Class Library Project") means that you are reference the exact same compiled version (stored in the DLL) in each project. Linking means that both executable's will contain their own copy of the compiled code. It is more common to use DLLs to share code as it means it only has to get compiled once. – chillitom Apr 09 '13 at 16:48
  • @chillitom: Thanks. The only issue I see with this is that I will have to constantly compile it to be able to use it in other projects, right? That would be heck-of-a inconvenient. – ahmd0 Apr 09 '13 at 16:52
  • 1
    If the projects are all in the same solution in VS then everything will get compiled as needed, nothing to think about. – chillitom Apr 09 '13 at 16:53
  • @chillitom: No, they are not. And the reason for that is -- I need to start debugging them both at the same time, which AFIK is not possible in a single solution. – ahmd0 Apr 09 '13 at 16:55
  • 1
    Right Click Solution->Set StartUp Projects->Multiple StartUp Projects then set both projects to start (works in VS2012 at least) – chillitom Apr 09 '13 at 17:06