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
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.
Multiple interface constraints can be specified. The constraining interface can also be generic.
Yes, you can define a generic method in a non-generic class in Java.
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.
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)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With