Search code examples
c#genericsmethodsreturn-typegeneric-method

Are mutiple methods recommended when returning different types?


I'm returning values from an Entity object. Some of them are String typed and some are not. Right now, I did a quick solution as follows.

private String GetStringValue(Entity entity, String attribute, String substitute = "")
{
  if(entity.Contains(attribute)
    return entity[attribute] as String;
  return substitute;
}

private String GetIntValue(Entity entity, String attribute, int substitute = 0)
{
  if(entity.Contains(attribute)
    return entity[attribute] as int;
  return substitute;
}

Then I remembered that there's a syntax for generic typing (something like <TypeX>). My question is, however, if there's a point to start changing the existing code. I'll need to change the signature of the method in two places (return type and substitute type) but I fear that I'll need to do some complex coding inside the method as well.

On the other hand, I'd have a nice way to treat all the types possible (and I have a hunch we'll be working with more than strings and integers.


Solution

  • You are right "something like" is the generic method. Check out generic methods there. Next method looks good for your purpose.

       private  static T GetValue<T>(Entity entity, string attribute, T defaultValue)
            {
                if (!entity.Contains(attribute))
                    return defaultValue;
    
                return  (T)entity[attribute];
            }
    

    EDIT: updated according of the w0lf's comment.