3

I have to write 3 functions which accepts a parameter of BaseClass type and then return a DerivedClasses as the return value.

Public DerivedClass1 SimpleTest1(BaseClass baseType)
{
DerivedClass1 derivedClass1 = new DerivedClass1();
derivedClass1.item = baseType.item;
derivedClass1.itemGroup = baseType.itemGroup;
return derivedClass1;
}

Public DerivedClass2 SimpleTest2(BaseClass baseType)
{
DerivedClass2 derivedClass2 = new DerivedClass2();
derivedClass2.item = baseType.item;
derivedClass2.itemGroup = baseType.itemGroup;
return derivedClass2;
}

Public DerivedClass3 SimpleTest3(BaseClass baseType)
{
DerivedClass3 derivedClass3 = new DerivedClass3();
derivedClass3.item = baseType.item;
derivedClass3.itemGroup = baseType.itemGroup;
return derivedClass3;
}

The code written in all the 3 methods is the same! Is there a better way to achieve this, without code duplication? Is there a specific design pattern that I can apply here?

papfan
  • 191
  • 2
  • 12

2 Answers2

4

Use generics on this and you can express it fairly nicely:

public T SimpleTest<T>(BaseClass baseType) where T : BaseClass, new()
{
    T derived = new T();
    derived.item = baseType.item;
    derived.itemGroup = baseType.itemGroup;
    return derived;
}

There is one caveat that you have to have a default constructor or else this won't work. In instances where you have a constructor with one or more arguments (but the same signature for each), you can dynamically instantiate the class using Reflection, as in dbaseman's answer.

Mike Bailey
  • 12,479
  • 14
  • 66
  • 123
  • Interesting. Any thoughts of pro, con of using new T() vs dbaseman's use of Activator.CreateInstance() ? – dreza Jun 19 '12 at 03:10
  • @dreza: According to [this](http://stackoverflow.com/a/1649108/312124) answer, there is none. – Mike Bailey Jun 19 '12 at 03:11
  • I think its better to have a where new() as it says something about what kind of type can be used. – Keith Nicholas Jun 19 '12 at 03:20
  • I'd also simplfy it down to public T SimpleTest(BaseClass baseType) where T:BaseClass, new() { return new T {Item = baseType.Item, ItemGroup = baseType.ItemGroup}; } – Keith Nicholas Jun 19 '12 at 03:23
2

This seems like a good application of generic functions ...

public T SimpleTest<T>(BaseClass baseType) where T : BaseClass
{
    T derivedClass = Activator.CreateInstance<T>();
    derivedClass.item = baseType.item;
    derivedClass.itemGroup = baseType.itemGroup;
    return derivedClass
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260