Dot NEt Kid
Dot NEt Kid

Reputation:

Generic method call

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericCount
{
    class Program
    {
        static int Count1<T>(T a) where T : IEnumerable<T>
        {
            return a.Count();
        }

        static void Main(string[] args)
        {
            List<string> mystring = new List<string>()
            {
                "rob","tx"
            };

            int count = Count1<List<string>>(mystring);******
            Console.WriteLine(count.ToString());

        }
    }
}

What do I have to change in the above indicated line of code to make it work. I am just trying to pass either List or array in order to get the count.

Upvotes: 1

Views: 264

Answers (4)

Jason Jackson
Jason Jackson

Reputation: 17260

Your generic constraint is wrong. You cannot enforce it to implement IEnumerabl<T>

Upvotes: 0

Jon Cahill
Jon Cahill

Reputation: 4988

Your count method is expecting a type of IEnumerable and then you have set T to be List which means the method will expect IEnumerable> which is not what you are passing in.

Instead you should restrict the parameter type to IEnumerable and you can leave T unconstrained.

namespace GenericCount
{
    class Program
    {
        static int Count1<T>(IEnumerable<T> a)
        {
            return a.Count();
        }

        static void Main(string[] args)
        {
            List<string> mystring = new List<string>()
        {
            "rob","tx"
        };

            int count = Count1(mystring);
             Console.WriteLine(count.ToString());

        }
    }
}

Upvotes: 0

Darren Kopp
Darren Kopp

Reputation: 77667

You want this

static int Count1<T>(IEnumerable<T> a)
{
    return a.Count();
}

Upvotes: 4

Brian
Brian

Reputation: 118925

You have "where T : IEnumerable<T>", which is not what you want. Change it to e.g. "IEnumerable<string>" and it will compile. In this case, "T" is List<string>, which is an IEnumerable<string>.

Upvotes: 0

Related Questions