natdanimore
natdanimore

Reputation: 39

How do I use an extension function in another class? C#

I've got a couple of extension functions that I want to transfer between classes.

I have a class called Helpers.cs that I want to have the following:

namespace XYZ
{
    public class Helpers
    {
        public static string Encrypt(this string plainText){
            //... do encrypting
        }
    }
}

In my other class Impliment.cs I want to have the following:

string s = "attack";
s.Encrypt();

How can I implement this?

Upvotes: 2

Views: 2218

Answers (3)

D Stanley
D Stanley

Reputation: 152521

You're close - extension methods need to be in a static class:

public static class Helpers
{
    public static string Encrypt(this string plainText){
        //... do encrypting
    }
}

If you tried what you posted you'd get a pretty clear compiler error that says basically the same thing:

Extension method must be defined in a non-generic static class

Note that your usage will be slightly different that what you want. You can't do:

string s = "attack";
s.Encrypt();

becasue strings are immutable. Best you can do is overwrite the existing varialbe or store the result in a new one:

string s = "attack";
s = s.Encrypt();  // overwrite

or

string s = "attack";
string s2 = s.Encrypt();  // new variable

Upvotes: 3

Felipe Oriani
Felipe Oriani

Reputation: 38598

To create an Extension Method, the class must be static, but in general it has to follow these rules:

  • The class must be public and static
  • The method must be public and static
  • The type you want to create the extension method, in C#, must have the first parameter with the this keyword before the parameter

In your case, change the class to be static , for sample:

public static class Helpers
{
    public static string Encrypt(this string plainText)
    {
         //... do encrypting
         // return a string;
    }
}

I also like to create the classes with name like Type and Extensions sufix, for sample: StringExtensions.cs, DateTimeExtensions.cs, etc.

Obs: Remember it is not a type method, it is just a static method, but you use as a method from a type.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You need to make the class, static as well and use a using statement.

Example

FileA.cs:

namespace XYZ {

    public static class Helpers {

        public static string Encrypt(this string plainText){
            //... do encrypting
            return plainText;
        }

    }

}

FileB.cs:

using XYZ;

public class MainClass {

    public static void Main() {
        string s = "input";
        s = s.Encrypt();
        Console.WriteLine(s);
    }

}

Upvotes: 2

Related Questions