tags:

views:

158

answers:

4
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.

A: 

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

Jason Jackson
A: 

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>.

Brian
+4  A: 

You want this

static int Count1<T>(IEnumerable<T> a)
{
    return a.Count();
}
Darren Kopp
Thanks!!That's the only thing I wanted to know.
A: 

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());

        }
    }
}
Jon Cahill