简体   繁体   中英

Generic function with convertable parameters

I want to write a generic function, that receives a list as a parameter. If the list is null it should return null. If the list contains valid items, it should return the first item. The function should work with all primitive data types like int, short, float, double etc...

In my example I use int:

var a = new List<int>();
a.Add(3);

Foo<int, int?>(a);
Foo<int, int?>(null);

private T Foo<G, T>(List<G> list)
{
    if(list != null && list.Count > 0)
    {
        return list[0];
    }
    else
    {
        return default(T);
    }
}

This unfortunately does not work, because I did not find a generic constraint, that proves the compiler, that int? can be converted to int and short? to short etc... I only want to call the function with the primitive data types and their nullable pendants and also string.

Any ideas about another solution? :-)

Edit:

It should also work with string. Otherwise Rene Vogts solution would work.

Simply change the return type of the method, you only need one generic parameter, restricted to be a (non-nullable) value type:

private T? Foo<T>(List<T> list) where T : struct
{
    return list?.Count > 0 ? (T?)list[0] : null;
}

I don't think it's possible to make a single method that also can handle reference types like string . But for reference types you can always use LINQ''s FirstOrDefault() and the null-conditional operator:

List<string> list...
var result = list?.FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM