tags:

views:

90

answers:

4

When we declare (example) List<T> I can understand the declaration, but suppose I declare

IEnumerable<T<T1, T2>>

What did I actually declare?

  1. Does it mean, IEnumerable<T> contains two generic types? (What is the way to use it?)

  2. Can I have deep nested level like Person<T<T2<T3<P1,P2>>>>?

Simple example will really helpful.

+4  A: 

Unless you've actually got a generic type called T, that won't work. You need a real type there, e.g.

IEnumerable<Dictionary<string, int>>

which is a sequence of Dictionary<string, int> references.

But yes, you can nest generics a lot - and it becomes pretty unreadable:

List<Dictionary<List<IEnumerable<string>>, Dictionary<int, int>>> aargh = null;
Jon Skeet
are u jon skeet? why did you change the title to tony the pony?
@csharpbaby: Yes, I'm Jon Skeet. See http://www.vimeo.com/7516539
Jon Skeet
Actually I am reading C# in depth in that you mentioned IEnumerable<KeyValuePair<TKey,TValue>> ,by reading that ,i raised this question.Thanks for clarification.
This is currently different from the accepted answer.
Ankur Goel
@Ankur: What do you mean, exactly?
Jon Skeet
+1  A: 

The above example will not compile. But you can embed Generic types within one another with something like this:

IEnumerable<IEnumerable<int>>

Which would be an enumerable of an enumerable of ints (which would act as a jagged 2 dimensional array).

Jake Pearson
+1  A: 

(1) You declared an IEnumerable that enumerates objects of type T<T1, T2>. For example, Hashtable<Int, String>.

(2) Sure you can!

Thomas
+4  A: 

If you have a class

public class Pair<T1, T2> { ... }

then you can declare a method

IEnumerable<Pair<int, string>> GetPairs();

i.e. a method that returns an enumerable of pairs where each pair consists of an int and a string.

Usage:

foreach (Pair<int, string> pair in GetPairs()) { ... }

You can also deeply nest these:

IEnumerable<Pair<int, Pair<string, string>>> GetPairs();

i.e. a method that returns an enumerable of pairs where each pair consists of an int and a pair of two strings.

This works with generics as well:

IEnumerable<Pair<T1, T2>> GetPairs<T1, T2>();

i.e. a method that returns an enumerable of pairs where each pair consists of a T1 and a T2.

But you cannot do this:

IEnumerable<T<T1, T2>> GetGenericPairs<T, T1, T2>();
dtb
Excellent buddy,Really helped me a lot. :) Thousand Thanks.