-1
public static IReadOnlyCollection<int> FillData(this string[] ids,  IReadonlyCollection<int> list)
{ 
    var dataList = list?.ToList() ?? new List<int>();

    foreach (var id in ids)
    {
        dataList.Add(int.Parse(id));
    }

    return datalist.AsReadOnly();
}

How to create Generic method in order to receive int and long for IReadOnlyCollection param and return the value based on requested type?

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
Radost
  • 131
  • 1
  • 11
  • 1
    `public static IReadOnlyCollection FillData(this string[] ids, IReadonlyCollection list) where T : struct, IComparable, IFormattable, IConvertible` - contrainst does not support OR operator yet for `int or long` but only AND with the comma • [Generics Level 1](https://www.tutorialspoint.com/csharp/csharp_generics.htm) • [Generics level 2](https://www.tutorialsteacher.com/csharp/csharp-generics) • [Generics in .NET](https://learn.microsoft.com/dotnet/standard/generics/) • [Generic classes and methods](https://learn.microsoft.com/dotnet/csharp/programming-guide/generics/) –  Aug 18 '21 at 08:54
  • 1
    Does this answer your question? [Creating a generic method in C#](https://stackoverflow.com/questions/2144495/creating-a-generic-method-in-c-sharp) and [Is there a constraint that restricts my generic method to numeric types?](https://stackoverflow.com/questions/32664/is-there-a-constraint-that-restricts-my-generic-method-to-numeric-types) –  Aug 18 '21 at 08:57
  • 2
    From [Preview Features in .NET 6 – Generic Math](https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/): *One long requested feature in .NET is the ability to use operators on generic types. Using static abstracts in interfaces and the new interfaces being exposed in .NET, you can now write this code [...]* –  Aug 18 '21 at 08:59
  • 1
    @OlivierRogier why did I not know this .net6 awesomeness, +1000 – TheGeneral Aug 18 '21 at 09:17

1 Answers1

1

Something like that should work

    public static IReadOnlyCollection<T> FillData<T>(this string[] ids, IReadOnlyCollection<T> list)
    {
        var dataList = list?.ToList() ?? new List<T>();

        foreach (var id in ids)
        {
            dataList.Add((T)Convert.ChangeType(id, typeof(T)));
        }

        return dataList.AsReadOnly();
    }

PS: But keep in mind maybe you have to consider the culture.

Klamsi
  • 846
  • 5
  • 16