I have the methods:
public MyReturnType MyMethod(Class1 arg)
{
//implementation
}
public MyReturnType MyMethod(Class2 arg)
{
//implementation
}
//...
public MyReturnType MyMethod(ClassN arg)
{
//implementation
}
decimal, string, DateTime in [Class1, … , ClassN]
and one common method:
public MyReturnType MyMethod(object obj)
{
if(obj == null)
throw new ArgumentNullException("obj");
if(obj is MyClass1)
return MyMethod((Class1)obj);
if(obj is MyClass2)
return MyMethod((Class2)obj);
//...
if(obj is MyClassN)
return MyMethod((ClassN)obj);
return MyMethod(obj.ToString()); //MyMethod(string) implemented.
}
How can i refactor this code? I can use attributes and component model, something like this:
public class MyAttribute : Attribute
{
public Type Type { get; set; }
}
public MyReturnType MyMethod(object obj)
{
if(obj == null)
throw new ArgumentNullException("obj");
var protperty = TypeDescriptor.GetProperties(this, new Attribute[] { new MyAttribute() })
.Cast<PropertyDescriptor>().FirstOrDefault(x =>
x.GetAttribute<MyAttribute>().Type.IsInstanceOfType(obj));
if (protperty != null)
return protperty.GetValue(obj) as MyReturnType;
return MyMethod(obj.ToString());
}
but it looks quite hard to understand and can create some bugs. For example if somebody declare method like
[MyAttribute(Type = ClassNplus1)]
public NotMyReturnType MyMethod(ClassNplus1 arg);
Any other ideas how to create extensible system, where adding new class is required only to add one method? (add code in one place)
I believe what you are trying to do is known as multiple dispatch (someone please correct me if I’m wrong) and this is not available in current versions of the .Net framework. However it is being introduced in .Net 4.0 via the dynamic keyword -> http://blogs.msdn.com/laurionb/archive/2009/08/13/multimethods-in-c-4-0-with-dynamic.aspx.