Extension methods on a static class? [duplicate]

妖精的绣舞 提交于 2019-12-04 02:28:20

You can't have extension methods on static classes because extension methods are only applicable to instantiable types and static classes cannot be instantiated.

Check this code..

    public static bool IsEmail(this string email)
    {
        if (email != null)
        {
            return Regex.IsMatch(email, "EmailPattern");
        }

        return false;
    }

First parameter to IsEmail() is the extending type instance and not just the type itself. You can never have an instance of a static type.

You can't extend static classes in C#. Extension methods work by defining static methods that appear as instance methods on some type. You can't define an extension method that extends a static class.

You might want to turn your static class into a singleton. Then there will only be one instance of the class. And you can use extension methods on it because it's an instance.

This is provided you have access to the source code of the class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!