generics c#
i know that if i have method or class at name means that it is generis and t can be of any type but what means when <> are at type name:
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{}
can you help me?
Please fix your spelling errors, and get the code so it looks right. You have to be very careful with left angle bracket characters <
. This looks like it could be an extension function, that can be called on any IEnumerable (which in Unity means on any coroutine), but it's hard to be sure.
Answer by jdean300 · May 17, 2017 at 09:33 PM
You mean something like IEnumerable<GameObject>
?
IEnumerable is defined as a generic interface - so it can operate on any type. If a function returns IEnumerable<GameObject>
it means it returns an IEnumerable of GameObjects, or essentially a sequence of GameObjects.
sorry i don't know why site cut part of code now is ok i was asking about why <> is at IEnumerable and at Combinations
Combinations<T>
says that this function is generic, and so T can be any type. I could call this as Combinations<GameObject>(...)
or Combinations<int>(...)
or really any type.
IEnumerable<T>
as the parameter says that you have to pass in an IEnumerable with the same T as the function is called with.
I think what is confusing you is that there are multiple T's. Is that the case? All that is saying is that all of these T's need to be the same type. For example, this is a correct call:
IEnumerable<IEnumerable<int>> ints = Combinations<int>(new int[]{1, 2, 3}, 2);
This call is incorrect because the T's are not the same:
IEnumerable<IEnumerable<int>> ints = Combinations<int>(new float[]{1.2f, 2f, 3.5f}, 2);
The names in the brackets after the function name, Combinations<T>
, Are what define the functions generic type paramaters. You can name them anything, and can have multiple of them. We could imagine a function like this:
public static IEnumerable<TObject> GetObjects<T$$anonymous$$ey, TObject>(this IEnumerable<T$$anonymous$$ey> keys)
This function has two generic type parameters: T$$anonymous$$ey, TObject
. The parameter has to be a IEnumerable<T$$anonymous$$ey>
, where T$$anonymous$$ey is the same thing as what the function is called with. Similarly, the return type has to use the same type as the second generic type paramter. So, this is a valid call: IEnumerable<GameObject> objs = GetObjects<string, GameObject>(new string[]{"a", "b"});
where as this call is invalid: IEnumerable<string> objs = GetObjects<string, GameObject>(new GameObject[]{gameObject});