Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraints are not allowed on non-generic declarations

Tags:

c#

.net

generics

I've had a look at the other similar questions but the issues were syntax errors. Perhaps I'm missing something but my syntax looks correct as far as I can tell. I'm trying to declare a method as follows:

internal IDictionary<string, T> FillObjects(
    IReadableRange<T> svc,
    Func<T, string> getKey) where T : BaseEntity
{
}

but am getting the compiler error:

constraints are not allowed on non-generic declarations

any ideas?

thanks

Matt

like image 519
mattpm Avatar asked Aug 22 '14 07:08

mattpm


People also ask

What are the constraints in generics?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.

Can a non-generic class have a generic method?

Yes, you can define a generic method in a non-generic class in Java.

What is generic type constraints in C#?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.


1 Answers

The problem is that your method does not define the generic type <T>. It just uses the type T given by the enclosing type.

And you can declare constraints only at the same place where you define generic parameters.

There are two solutions:

1., You should either define generic parameters on the function:

public class EnclosingType
{
    internal IDictionary<string, T> FillObjects<T>(
        IReadableRange<T> svc,
        Func<T, string> getKey) where T : BaseEntity
    {
    }
}

In your case it doesn't compile, because you EnclosingType is probably the EnclosingType<T> that leads to an ambiguity between EnclosingType's T and FillObjects' T:

2., Or you could just define the constraints on the enclosing type:

public class EnclosingType<T>
    where T : BaseEntity
{
    internal IDictionary<string, T> FillObjects(
         IReadableRange<T> svc,
         Func<T, string> getKey)
    {
    }
}
like image 96
Eugene Podskal Avatar answered Oct 05 '22 09:10

Eugene Podskal