Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert System.Func<Tderived, bool> to System/Func<Tbase, bool>

I've googled but couldn't find satisfactory answers. I'm basically trying to get this code to work:

public List<WordEntry> WordDataBase = new List<WordEntry>();
public List<CharacterEntry> CharacterDataBase = new List<CharacterEntry>();

public List<Entry> SelectWhere<T>(System.Func<T, bool> predicate) where T : Entry
{
    if (typeof(T) == typeof(WordEntry))
        return WordDataBase.Where(predicate);
    else if (typeof(T) == typeof(CharacterEntry))
        return CharacterDataBase.Where(predicate);
    else
        return null;
} 

In this sample, both WordEntry and CharacterEntry are derived from Entry. I get the compiler errors:

Error   CS1503  Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<WordEntry, int, bool>'   

and

Error   CS1503  Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<CharacterEntry, int, bool>'

Hopefully you can help me with this. Thanks in advance

like image 278
user1370286 Avatar asked Nov 26 '25 12:11

user1370286


1 Answers

Basically, you just need to cast - the language rules don't allow the compiler to take the if statement into account when it thinks about the types involved. Note that you also need to call ToList<Entry>(), specifying the type argument to avoid getting a List<WordEntry> or List<CharacterEntry>:

public List<Entry> SelectWhere<T>(Func<T, bool> predicate) where T : Entry
{
    if (typeof(T) == typeof(WordEntry))
        return WordDataBase
            .Where((Func<WordEntry, bool>) predicate)
            .ToList<Entry>();
    else if (typeof(T) == typeof(CharacterEntry))
        return CharacterDataBase
            .Where((Func<CharacterEntry, bool>) predicate)
            .ToList<Entry>();
    else
        return null;
}

I'd suggest that rather than making this generic though, you might want to just have two different methods instead. It doesn't feel like it's really a generic method, given that it only works with two very specific types.

like image 121
Jon Skeet Avatar answered Nov 28 '25 02:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!