zokocx zokocx - 1 year ago 195
C# Question

The type cannot be used as type 'T' in the generic type or method. There is no implicit reference conversion from to

I'm trying to write a generic method to check if List is null or empty and throw an exception.

This is what I have:

public static void IsNullOrEmpty<T>(T argument) where T : List<T>
if (argument == null || argument.Count == 0)
throw new ArgumentException("Argument " + nameof(argument) + " can't be null or empty list.");

The problem is with calling this method; I trying to call this method like this:


Where options.Parameters is type of:

I'm getting this error:

There is no implicit reference conversion from 'System.Collections.Generic.List<ParameterServiceReference.Parameter>' to 'System.Collections.Generic.List<System.Collections.Generic.List<ParameterServiceReference.Parameter>>

If I call method like this:


I get this error:

cannot convert from 'System.Collections.Generic.List<Project.Layer.ParameterServiceReference.Parameter>' to 'Project.Layer.ParameterServiceReference.Parameter'

Is this kind of generic method possible with generic collection or not, in the solution I will have many generic lists of different classes and I think it's not smart to write so many overloaded methods.

Answer Source

You generic constraint specifically says that the parameter needs to be some type that is a List where the generic type of the list is itself. When you say where T : List<T> you're saying that the generic argument, T, needs to be a List<T> where T is the type you're adding the constraint for.

What you should really do here is just have the method accept a List<T>, not a T where T is a List:

public static void IsNullOrEmpty<T>(List<T> argument) { //...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download