0

I have a method like that:

private Contact GetContactFromDbReaderWithSingleResult(DbDataReader dbReader)
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<Contact>(dbReader)[0];
    }

    return null;
}

and then I could have a quite similar method like that:

private Email GetEmailFromDbReaderWithSingleResult(DbDataReader dbReader)
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<Email>(dbReader)[0];
    }

    return null;
}

The signature of the DataReaderToEntity-Method is:

public List<T> DataReaderToEntity<T>(IDataReader dr) where T : new()

Now I want to create a generic variant GetGenericEntityFromDbReaderWithSingleResullt.

My approach looks like that, but it's not correct:

private object? GetEntityFromDbReaderWithSingleResult<T>(DbDataReader dbReader)
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<typeof(T)>(dbReader)[0];
    }

    return null;
}

Still learning to deal with generics though... What am I doing wrong?

Thank in advance!

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
iquellis
  • 979
  • 1
  • 8
  • 26

1 Answers1

4

Change your return type to T instead of object and remove the typeof:

private T GetEntityFromDbReaderWithSingleResult<T>(DbDataReader dbReader) where T : new()
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<T>(dbReader)[0];
    }

    return default(T);
}
AGB
  • 2,378
  • 21
  • 37
  • @HimBromBeere T might be a value type though which would not be nullable. – AGB Aug 10 '17 at 10:16
  • @HimBromBeere No you can't. Your code even would compile. You would get a message like **"Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead."** Have a look at [How can I return NULL from a generic method in C#?](https://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c) – Mighty Badaboom Aug 10 '17 at 10:17
  • Tried that before, does not work, compiler says: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'DataReaderReflection.DataReaderToEntity(IDataReader)' – iquellis Aug 10 '17 at 10:30
  • Your method needs to have where T : new() as well. I've updated my answer. – AGB Aug 10 '17 at 10:36
  • Yes, thanks. I deleted my correction post after you changed your example. Thank you so much! – iquellis Aug 10 '17 at 10:40