Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the generic type 'System.Collections.Generic.IEnumerable<T> requires 1 type arguments

Tags:

c#

My Code in C# is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cs
{
    public class TreeNode<T> : IEnumerable
    {
    }

And I got error here:

Error 1 Using the generic type 'System.Collections.Generic.IEnumerable<T>' requires 1 type arguments

like image 690
Mohammad Ali Avatar asked Feb 04 '15 06:02

Mohammad Ali


4 Answers

Interface IEnumerable is declared in System.Collections, so following should be added:

using System.Collections;

There is also a similar interface, IEnumerable<T>, which is a generic version of IEnumerable and that one is declared in System.Collections.Generic and that is why Visual Studio gives you such a mysterious error.

like image 91
Dmytro Zakharov Avatar answered Nov 11 '22 05:11

Dmytro Zakharov


There are two "versions" of IEnumerable.

One is the nongeneric System.Collections.IEnumerable. This is provided mostly for backwards compatibility. I can't really think of a good reason to make new classes directly inherit from it.

The other is the generic one, System.Collections.Generic.IEnumerable<T>. This implements IEnumerable as well, so it's a better choice in all cases.

When an interface has a generic overload, you need to specify that generic type parameter. In your case,

public class TreeNode<T> : IEnumerable<T>

It's worth noting that when you implement this, you'll need to implement two methods:

Enumerator<T> GetEnumerator(); // From IEnumerable<T>
Enumerator IEnumerable.GetEnumerator(); // From IEnumerable

It's not too unusual too return this.GetEnumerator() from the second one, since again, it's provided mostly as backwards-compatibility. You always want those two enumerators to return the same data, so that's a nice and easy solution.

like image 22
Matthew Haugen Avatar answered Nov 11 '22 07:11

Matthew Haugen


You should use:

System.Collections.IEnumerable

instead of

IEnumerable

or

System.Collections.Generic.IEnumerable
like image 42
T.Todua Avatar answered Nov 11 '22 07:11

T.Todua


You either need to

  • use non-generic version of IEnumerable which is located in System.Collection namespace (which you did not include)
  • specify type for generic version (more likely)

Sample for generic version:

class TreeNode<T> : IEnumerable<T> 
{....}
like image 2
Alexei Levenkov Avatar answered Nov 11 '22 07:11

Alexei Levenkov