Why won’t my generic method compile?

C

Carl Johansson

Why won’t my generic method compile?

private static void PrintTable<T>(Table<T> table, string text)
{
Console.WriteLine(text);

foreach (T record in table)
Console.WriteLine(record);
}

The complier reports the following error:

“The type 'T' must be a reference type in order to use it as parameter
'TEntity' in the generic type or method
'System.Data.Linq.Table<TEntity>.”

Looking at the definition of the Table<TEntity> class, it is clear
that it has a constraint which says the type parameter must be a class
(“where TEntity : class”). However, how does the compiler know
beforehand that I will be calling the “PrintMethod<T>()” method
passing on a non class (which I won’t!)?

Regards Carl Johansson
 
C

Carl Johansson

Why won’t my generic method compile?

I found the very simple solution myself! :)

The generic method must honour the same contraint as placed on the
generic class. That is, instead of declaring the method like this:

private static void PrintTable<T>(Table<T> table, string text)
{
Console.WriteLine(text);

foreach (T record in table)
Console.WriteLine(record);
}

It works just the way I expected when declared like this:

private static void PrintTable<T>(Table<T> table, string text)
where T: class
{
Console.WriteLine(text);

foreach (T record in table)
Console.WriteLine(record);
}

Regards Carl Johansson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top