I have to say that the title is too poor to be able to describe the problem but that was the only thing I could think of. Anyway, suppose I've been given the following enum:
public enum DocumentType{
IdCard=0,
Passport,
DriversLicense
}
And I have a method that accepts a string and returns the above enum:
public DocumentType GetDocTypeByString(string docType){
switch (docType)
{
case "ID":
return DocumentType.IdCard;
case "PASS"
return DocumentType.Passport;
//and so on
}
}
Now, what if the passed string does not meet any of the switch conditions? The silliest thing would be to make the return type object, but that's something that hardly ever somebody would do it. if the enum was mine, I would add an additional value called something like "None" and return that in case of no match, but I have no control on it. Then I thought, whether it would be possible to constrain the input to certain values. As far as the C# is concerned, I am almost totally sure that it's not possible, but I decided to ask anyway. Would would you recommend in this case?
No you can't. The pattern normally used is to throw a
throw new ArgumentException("docType");
Technically even a
throw new ArgumentOutOfRangeException("docType");
would be correct, but I haven't ever seen it used outside "numeric" indexes.
For example, Enum.Parse
throw an ArgumentException
if you use illegal values, and your method seems to be something very similar to that.
Other option is to use the Enum.TryParse
pattern:
public static bool TryGetDocTypeByString(string docType, out DocumentType documentType)
{
switch (docType)
{
case "ID":
documentType = DocumentType.IdCard;
return true;
case "PASS"
documentType = DocumentType.Passport;
return true;
}
documentType = default(DocumentType);
return false;
}
You could make the return type nullable and do like so:
public DocumentType? GetDocTypeByString(string docType){
switch (docType)
{
case "ID":
return DocumentType.IdCard;
case "PASS"
return DocumentType.Passport;
//and so on
default: return null;
}
}
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