kunichhua2
kunichhua2

Reputation: 31

How to add an extension method to .Net assembly?

I am new to software development and may be I am asking a very silly question but, I am curious to learn more on this thing. Is it possible to add an extension method to .Net assembly? I want my extension method to work on every project I am working on. Apart from referencing to my own assembly, is there any other way?

If it is not possible, please explain taking some time.

Thanks in advance :)

Upvotes: 1

Views: 2399

Answers (4)

Sayse
Sayse

Reputation: 43320

  1. Create a new project as a dll (class library)
  2. Add your extention classes/methods to this dll
  3. Reference this dll in your future projects

In response to your comment, you cannot modify the .net framework, only build your own dll's to include methods you wish to share between projects.

The reason you cannot modify the framework is because the code has been compiled already.

Upvotes: 1

JSJ
JSJ

Reputation: 5691

Is it possible to add an extension method to .Net assembly? this itself says that you have to create your own methods to extend .Net assembly which are already deployed. The only way to use is define your own methods and include the namespace in the code where you will use these extenssion methods.

sample. of Extenssion methods.

using system;
namespace myNamespace
{
      public static class MyExtMethods
       {
    public static string Foo(this string bar)
           {
             return bar+ "Some values added. ";

           }
        }
}

Uses of Extenssion Method.

using system;
using myNamespace;
    namespace myNamespace2
    {
          public class Program
           {
        public static void Main(string[] args)
               {
                string str ="Some Value";
               Console.WriteLine(str.Foo());

               }
            }
    }

Upvotes: -1

MSTdev
MSTdev

Reputation: 4635

You can create extensible method in class but not possible in your reference dll please check here extensible class method

Upvotes: 0

ChrisF
ChrisF

Reputation: 137168

There's no way of adding methods to an existing assembly.

There's no other way than creating it in your own assembly and referencing that.

Upvotes: 2

Related Questions