-2

I have a function which takes an object parameter say entity and returns concrete objects like below. The concrete objects inherits from IEntity.

        public IEntity GetEntity(object entity) 
        {
            if(entity is A) { .... return new Customer(); }
            else if(entity is B) {... return new Invoice(); }
            .......
        }

This obviously works but I was wondering if this is the best approach or is there any other alternative and recommended way from architecture perspective?

Thanks!

Deepak Agarwal
  • 458
  • 1
  • 4
  • 18
  • 1
    To determine the proper approach, you need to explain why you have this method in the first place. – CodeCaster Jan 12 '16 at 15:03
  • 1
    @DeepakAgarwal `Activator.CreateInstance(entity.GetType());` can be more accurate way to write above code. – tchelidze Jan 12 '16 at 15:05
  • 1
    Why do you even need this? I suspect the architectural concern is what drove the need for this method, not the method itself. – David Jan 12 '16 at 15:06
  • Possible duplicate of [Get a new object instance from a Type](http://stackoverflow.com/questions/752/get-a-new-object-instance-from-a-type) – MakePeaceGreatAgain Jan 12 '16 at 15:06
  • Sorry for the confusion. The same entity names of different namespaces might have created the confusion here. I've edited the code now. – Deepak Agarwal Jan 12 '16 at 15:48

1 Answers1

1

You could use generics:

public IEntity GetEntity<T>(T entity)
    where T : IEntity, new()
{
    return new T();
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • 3
    Wheher this is or isn't a valid approach depends on how OP calls this code. That's why this question is currently too broad and should not be answered; I can think of twenty possible approaches, all which can or cannot be relevant to OP - we need more input. – CodeCaster Jan 12 '16 at 15:06
  • 1
    If the consuming code only knows that the type is an `object` then wouldn't this result in a new instance of `Object`? – David Jan 12 '16 at 15:07
  • 1
    @David no, you cannot call this with an `object` reference, because `object !: IEntity`. – CodeCaster Jan 12 '16 at 15:07
  • 1
    @tchelidze don't suggest [edits like that](http://stackoverflow.com/review/suggested-edits/10866386). You're deviating from what OP tried to say in their answer. If you think the answer is incorrect, post a comment. – CodeCaster Jan 12 '16 at 15:08
  • 1
    @CodeCaster Thanks, i'll take into account. – tchelidze Jan 12 '16 at 15:15
  • Please refer edited code. Sorry for confusion. – Deepak Agarwal Jan 12 '16 at 15:49