Let's assume I have two classes that look like this (the first block of code and the general problem are related to C#):
class A
{
public int IntProperty { get; set; }
}
class B
{
public int IntProperty { get; set; }
}
These classes cannot be changed in any way (they are part of a 3rd party assembly). Therefore, I cannot make them implement the same interface, or inherit the same class that would then contain IntProperty.
I want to apply some logic on the IntProperty
property of both classes, and in C++ I could use a template class to do that quite easily:
template <class T>
class LogicToBeApplied
{
public:
void T CreateElement();
};
template <class T>
T LogicToBeApplied<T>::CreateElement()
{
T retVal;
retVal.IntProperty = 50;
return retVal;
}
And then I could do something like this:
LogicToBeApplied<ClassA> classALogic;
LogicToBeApplied<ClassB> classBLogic;
ClassA classAElement = classALogic.CreateElement();
ClassB classBElement = classBLogic.CreateElement();
That way I could create a single generic factory class that would work for both ClassA and ClassB.
However, in C#, I have to write two classes with two different where
clauses even though the code for the logic is exactly the same:
public class LogicAToBeApplied<T> where T : ClassA, new()
{
public T CreateElement()
{
T retVal = new T();
retVal.IntProperty = 50;
return retVal;
}
}
public class LogicBToBeApplied<T> where T : ClassB, new()
{
public T CreateElement()
{
T retVal = new T();
retVal.IntProperty = 50;
return retVal;
}
}
I know that if I want to have different classes in the where
clause, they need to be related, i.e. to inherit the same class, if I want to apply the same code to them in the sense that I described above. It is just that it is very annoying to have two completely identical methods. I also do not want to use reflection because of the performance issues.
Can somebody suggest some approach where this can be written in a more elegant fashion?