I have a few methods like the following
public static string RequestEntry (string name)
{
if (name == "John" || name == "Bob" || name == "Ken")
return $"Hello {name}, you may enter";
return $"Get out of here {name}, no one like you!";
}
public static string Kiddify (string name)
{
if (name == "John" || name == "Bob" || name == "Ken")
return $"{name}{name[^1]}y";
return $"Get out of here {name}, no one like you!";
}
Note: These are only meant to demonstrate a concept and not the purposes of my real methods. My real methods have their own isolated functionality.)
My issues with this is:
- I am a very bad typer/speller and will most likely mistype the string that pass into this method, which could introduce bugs.
- I don't want there to be a default case, because I have specific input string I want to work with.
- Programming is a hobby. I will sometimes go weeks without having time to code and remembering the valid strings I can pass is highly unlikely.
So, I thought to use an enum
public enum Name{
John,
Bob,
Ken
}
and implement the methods as follows
public static string RequestEntry (Name name)
{
string sName = name switch
{
Name.John => "John",
Name.Bob => "Bob",
Name.Ken => "Ken",
_ => throw new NotImplementedException()
};
return $"Hello {sName}, you may enter";
}
public static string Kiddify (Name name)
{
return name switch
{
Name.John => "Johnny",
Name.Bob => "Bobby",
Name.Ken => "Kenny",
_ => throw new NotImplementedException()
};
}
I feel like this would be pretty common practice, and it solves all my above issues. Now my issue is that modifying Names
will mean I also have to modify my class methods to deal with the changes.
And finally, we get to the question. Is there another way I do this?
I considered using reflection and attributes to assign string values to the different names in the enum
, but I would have to assign a different string attribute for each use case. I don't like that idea and don't like using reflection if at all possible.
CodePudding user response:
Why not organize names into a collection? For instance
private static readonly HashSet<string> s_Names = new() {
"John", "Bob", "Ken"
};
public static string RequestEntry (string name) =>
s_Names.Contains(name)
? $"Hello {name}, you may enter"
: $"Get out of here {name}, no one like you!";
CodePudding user response:
You can use the Enum.ToString
method to get the string "John"
from an enum. For example:
Names.John.ToString()
You can use your Kiddify
method on this string afterwards.
(The opposite is Enum.TryParse
which will get the enum
value from a string
. )