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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With