Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

Tags:

c#

I am getting compile error error "The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?

Below is my code:

static class ExtensionMethods
{
    public static Collection<T> ToCollection(this IEnumerable<T> source)
    {
        Collection<T> sourceCollection = new Collection<T>();

        foreach (T currentSourceInstance in source)
        {
            sourceCollection.Add(currentSourceInstance);
        }

        return sourceCollection;
    }
} 
like image 813
iCreator Avatar asked Dec 14 '13 13:12

iCreator


1 Answers

Change it to this:

public static class ExtensionMethods
{
    public static Collection<T> ToCollection<T>(this IEnumerable<T> source)
    {
        Collection<T> sourceCollection = new Collection<T>();

        foreach (T currentSourceInstance in source)
        {
            sourceCollection.Add(currentSourceInstance);
        }

        return sourceCollection;
    }
} 

Notice the ToCollection<T>, otherwise the compiler doesn't understand where this T is coming from.

You can call it like this (where Thing is your custom type in this example):

var items = new List<Thing>();
var collection = items.ToCollection<Thing>();
like image 179
Aage Avatar answered Oct 27 '22 11:10

Aage