Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a .NET extension method with solution scope

I have a few 'helper' style extension methods I use quite regularly now (they are mostly quite simple, intuitive, and work for good not evil, so please don't have this descend into a discussion around whether or not I should use them). They are largely extending core .NET CLR classes.

Currently, I have to copy the 'ExtensionMethods.cs' file that holds my extension methods to each new project within a solution to be able to use them in multiple projects.

Is it possible to define an extension to work over multiple projects within a solution, or wrap them in an 'extensions' dll, or are they confined to the scope of project?

EDIT Whilst the 'dedicated project' answers are perfectly valid, I chose marxidad's as I prefer the approach he gives. Thanks for all the answers so far, and I have upmodded them all, as they were all good answers

like image 858
johnc Avatar asked Oct 02 '08 03:10

johnc


People also ask

Can I add extension methods to system object in NET Framework?

All types in the .NET Framework inherit from System.Object. For this reason, it is strongly advised not to add extension methods to System.Object. Adding an extension to System.Object could have inconsistent behavior and increase the possibility of errors when an existing type method is called instead of the extension method.

What is an extension method?

Last Updated : 01 May, 2019 In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0.

What is the scope of the extension method printandpunctuate?

The extension method must be in scope when it is called. Extension method PrintAndPunctuate extends the String class with a method that displays the string instance followed by a string of punctuation symbols sent in as a parameter.

How do I create an extension method in Visual Studio?

Open a new or existing Visual Basic application in Visual Studio. At the top of the file in which you want to define an extension method, include the following import statement: Within a module in your new or existing application, begin the method definition with the <Extension> attribute:


1 Answers

If you don't want to create a whole project just for the extension methods, you can link the same file into separate projects without copying the file:

  1. In Solution Explorer, select the target project.
  2. Select the Project menu.
  3. Select Add Existing Item.
  4. In the Add Existing Item dialog box, select the item you want to link.
  5. From the Open button drop-down list, select Add As Link.
like image 82
Mark Cidade Avatar answered Sep 22 '22 23:09

Mark Cidade