Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override ToString() on enum in C#? [duplicate]

I have the following enum declared outside all the classes and namespaces in my project:

public enum ServerType { Database, Web } // there are more but omitted for brevity

I want to override the ToString() method with something like:

public override string ToString(ServerType ServerType)
{
    switch (ServerType)
    {
        case ServerType.Database:
            return "Database server";
        case ServerType.Web:
            return "Web server";
    }
    // other ones, just use the base method
    return ServerType.ToString();
}

However I get an error no suitable method found to override

Is it possible to override the enum when converting to string with my own method?

like image 948
Mark Allison Avatar asked Oct 19 '22 00:10

Mark Allison


1 Answers

You can define a static class then use it. when you create this static class and reference to your project, you can see extended ToString() method in all string variables. It is an easy way to extend variables. You can use it for other options ;)

    public static class Extenders
    {
        public static string ToString(this string text, ServerType ServerType)
        {
            switch (ServerType)
            {
                case ServerType.Database:
                    return "Database server";
                case ServerType.Web:
                    return "Web server";
            }
            // other ones, just use the base method
            return ServerType.ToString();
        }
    }

use it like Below;

 "Merhaba".ToString(ServerType.Database);
like image 51
Ahmet Almış Avatar answered Oct 27 '22 11:10

Ahmet Almış