Search code examples
c#extension-function

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?


Solution

  • 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