8

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?

Mark Allison
  • 6,838
  • 33
  • 102
  • 151
  • make your method extension - `public static string ToMyString(this ServerType ServerType)`. Then use it `_serverTypevariable.ToMyString();` – Fabio Oct 03 '16 at 14:08
  • https://social.msdn.microsoft.com/Forums/vstudio/en-US/54b4e56e-f062-4b8b-aac6-30e8b04e8720/overriding-tostring-method-for-enumerations-in-c?forum=csharpgeneral – MethodMan Oct 03 '16 at 14:09
  • 2
    already answered here http://stackoverflow.com/questions/479410/enum-tostring-with-user-friendly-strings – hjgraca Feb 06 '17 at 11:20

1 Answers1

5

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);