Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I put a constraint on a literal string parameter

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?

like image 735
Mikayil Abdullayev Avatar asked Dec 15 '22 14:12

Mikayil Abdullayev


2 Answers

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;
}
like image 143
xanatos Avatar answered Dec 26 '22 00:12

xanatos


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;
    }
}
like image 28
Florian Gl Avatar answered Dec 26 '22 00:12

Florian Gl