I am currently using this type of code:
private void FillObject(Object MainObject, Foo Arg1, Bar Arg2) { if (MainObject is SomeClassType1) { SomeClassType1 HelpObject = (SomeClassType1)MainObject; HelpObject.Property1 = Arg1; HelpObject.Property2 = Arg2; } else if (MainObject is SomeClassType2) { SomeClassType2 HelpObject = (SomeClassType2)MainObject; HelpObject.Property1 = Arg1; HelpObject.Property2 = Arg2; } }
Assuming SomeClassType1 and SomeClassType2 have the same set of properties that I want to assign (although they may differ in others), is it possible to dynamically distinguish MainObject to the appropriate type and then assign the value without duplicating the code? Here is what I would like to see at the end:
private void FillObject(Object MainObject, Foo Arg1, Bar Arg2) { Type DynamicType = null; if (MainObject is SomeClassType1) { DynamicType = typeof(SomeClassType1); } else if (MainObject is SomeClassType2) { DynamicType = typeof(SomeClassType2); } DynamicType HelpObject = (DynamicType)MainObject; HelpObject.Property1 = Arg1; HelpObject.Property2 = Arg2; }
And, obviously, C # complains about the inability to find DynamicType:
Unable to find the name of the type or namespace DynamicType (are you missing the using directive or assembly references?)
Is this possible in C # 2.0? If this is messier than my current code, than I don't see the point in this, but I'm very interested to know. Thanks!
EDIT: just for clarification, I understand very well that implementing an interface is the most appropriate and probably the right solution. However, I'm more interested in how I could do this without implementing an interface. Thanks for the great answers!
c # dynamic-cast
MK_Dev
source share