I have a .cs
file full of C# code I keep reusing in multiple projects.
Right now I'm including it in these projects by copying and pasting the code into a new file in each project directory. This is the wrong way to do it.
What's the right way to do it?
The right way should:
- keep the common code in only one place on my computer
- and keep the link fresh --- so when the common code changes, each project is aware of it, the next time I recompile that project.
Randomly guessing, I'd expect some sort of directive like using mycode = C:\common\mycode.cs
, but I'm sure that's not the .NET way of doing things.
(I'm using C# 2010, .NET 4.0, and only compiling this code locally on one computer.)
Create a Class Library, add the file, build the project, and reference the DLL created from the build. Add the using statement to each file that will reference it. Also if it errors and the DLL is in the Project you and Right Click on the object -> Resolve and it will add the using for you.
Put the code into a separate class library project and reference that in your other projects.
Or,
- Right-Click on the project in Solution explorer
- Select Add Existing Item
- Browse to the .cs file in another project, and Single-click to select the file
- Click the down-arrow button to the right of Add and select Add as Link
You now have one source file referenced by two projects but it has the namespace you gave it in the first project which might not be ideal.
The best way of organizing that is to as the two other answers have suggested, put common code in a class library so it has a namespace of MyClassLibrary rather than SomeOtherProject. It saves a larger dll being copied which doesn't matter much until you come to develop for something small like Windows Phone. Or change the namespace of common code to be Me.Common in all your apps - it doesn't really matter which one is the original, you can edit it from any project that references it.
Check that Source Control isn't a problem.
I wrote an app that automates adding a code as a link, handy for projects that reuse a lot of code and change a bit. It's at https://github.com/CADbloke/CodeLinker
or
Don't be afraid to edit XML .csproj files. For instance, this works ...
<Compile Include="$(Codez)\z.Libraries\diff-match-patch\DiffMatchPatch\**\*.cs"
Exclude="NotThisOne.cs;**\NotThisFolderWith\This*.cs">
<Link>Libs\%(RecursiveDir)%(Filename)%(Extension)</Link>
</Compile>
...and will give you all the C# files from the source folder, and subfolders, as linked files in your destination project.
$(Codez)
is a Windows Environment Variable I use on my PCs.
- I also could have used
*.*
at the end instead of *.cs
.
- This is one of those things Visual Studio might break on you, adding a file into the folder full of wildcard-linked files may break them out to separate entries. Or not. Depends on the wind.