Home > other >  how to use more than one generic in a function in C#
how to use more than one generic in a function in C#

Time:12-31

I want to use more than one generic for a function but this doesn't work

  protected async Task<Tlist,T> Send<Tlist,T>(string url,HttpMethod method,DateTimeSyncedAt ) where Tlist,T:class
    {
    }

I get these error

CodePudding user response:

Task won't support giving back multiple types as return value.

So you can use it as basically like

Task<T>
//The following wont work
Task<T,T1>

But you can do with using tuples or anything that is value pair

** Value Pairs **

Tuples:

A tuple is a data structure that has a specific number and sequence of values. The Tuple<T1,T2> class represents a 2-tuple, or pair, which is a tuple Tuples are usually used by their operator (T, T1) Types in tuples could be more than two this depends on the use case.

Dictionaries:

Dictionary in C# is the generic collection type in the System.Collection.Generics namespace that contains Keys and Values.

Dictornary could be initialized by:

    new Dictionary<string, string>(new []{new KeyValuePair<string, string>("SOMETHING1","SOMETHING2")});

If you wrap this dictionary to a variable our case called dictionary you can access the keys and the values separately by the following

dictionary.Keys // this is an array of keys in the dictionary
dictionary.Values // this is an array of values in the dictionary

Do this as the following:

    protected async Task<(TList, T)> Send<TList,T>(string aParam,string bParam, string cParam) where TList : IEnumerable<T> where T : struct
    {
    }

This will return a tuple with the specified types in this case (item1: LIST_OF_GUID, GUID)

But you can use this with any type of constrains

  •  Tags:  
  • c#
  • Related