Question

I have one Generic Method, where we can pass a T as a interface type. Method returns a list of data corresponding T type. I have 20-25 same condition for this method how can I optimize logic.

Class implements interface. example Student class implements IStudent interface.

public ObservableCollection<T> GetAll<T>()
    {
        try
        {
            if (typeof(T) == typeof(IStudent))
            {                 
                return GetAll<T, Student>();
            }
            else if (typeof(T) == typeof(IZone))
            {
                return GetAll<T, Zone>();
            }
            else if (typeof(T) == typeof(IEmployee))
            {
                return GetAll<T, Employee>();
            }
            else if (typeof(T) == typeof(ICourse))
            {
                return GetAll<T, Course>();
            }
         }
    }

Here caller pass interface type T and I check type of T. I pass to other function T and class which will return list of T. Other function in base class which I can not change. Could anyone suggest me something about same.

Was it helpful?

Solution 2

You could try and do this through reflection.

public ObservableCollection<T> GetAll<T>()
{
    var typeName = typeof(T).FullName;
    var indexOfDot = typeName.LastIndexOf('.');
    var newTypeName = typeName.SubString(0, indexOfDot) + '.' + typeName.SubString(indexOfDot + 1);
    var newType = Type.GetType(newTypeName);
    var methodTypes = new [] { typeof(T), newType };
    var method = GetType().GetMethod("GetAll");
    var typedMethod = method.MakeGenericMethod(methodTypes);
    return (ObservableCollection<T>) typedMethod.Invoke(this, new object[0]);
}

Not pretty, but should do the job and does is generically.

The only caveat the current way is that the GetAll method is overloaded by generic parameters, so it may not get you the right method, or fail because there are two. I'll have a look if the right one can be indicated.

OTHER TIPS

I think you don"t need generic at all, you can create a common interface implemented by all your types :

public interface IObservableElement
{
    public ObservableCollection<IObservableElement> GetAll();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top