9

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?

3

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.