Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make reference to C# code from multiple projects

Tags:

c#

code-reuse

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.)

like image 576
Joe Avatar asked Feb 09 '12 22:02

Joe


People also ask

How do you declare a reference in C?

References in C++ A variable can be declared as a reference by putting '&' in the declaration.

Can we use reference in C?

No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.

What does reference mean C?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.

What is reference operator in C?

The reference operator noted by ampersand ("&"), is also a unary operator in c languages that uses for assign address of the variables. It returns the pointer address of the variable. This is called "referencing" operater.


2 Answers

Put the code into a separate class library project and reference that in your other projects.

like image 88
BrokenGlass Avatar answered Sep 20 '22 00:09

BrokenGlass


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.

like image 26
amaca Avatar answered Sep 21 '22 00:09

amaca