Home > database >  C# Calling methods inside of a generic method by comparing T with MyClasses
C# Calling methods inside of a generic method by comparing T with MyClasses

Time:06-11

I have some classes, for example:

class Contract
{
    public int id;
    public string num;
    public double value;
    public bool isnew;
    public bool toupdate;
    ...
}

class Attachment
{
    public int id;
    public int year;
    public int finance;
    public double value;
    ...
}

When I call a MySqlDataReader.Read() I want to call it by a generic function, that returns a List. Instead of making a method for every Class, I want something like this:

public List<T> ReadAs<T>()
{
    List<T> result;
    switch (T){
        case Contract: { result = ReadAsContract(); DoSomething1(); break; }
        case Attachment: { result = ReadASAttachment(); DoSomething2(); break; }
    }
    return result;
}

private List<Contract> ReadAsContract() {...here i make call MySqlDataReader.Read() and make list of instances...}
private List<Attachment> ReadAsAttachment() {...here i make call MySqlDataReader.Read() and make list of instances...}

So my questionis: is it even possible to make something like I described? Or is it better to make lots of ReadAsMyClass methods and call every time the exact one?

CodePudding user response:

This can be useful maybe,

public List<T> ReadAs<T>()
{
    var type = typeof(T);
    List<T> result = null;
    switch (type.Name)
    {
        case "Contract": { 
            result = ReadAsContract().Cast<T>().ToList();
            DoSomething1(); break;
        }
        case "Attachment": {
            result = ReadAsAttachment().Cast<T>().ToList();
            DoSomething2(); break;
        }
    }
    return result;
}
  • Related