Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

Use abstract generic type in c# and requires 1 type arguments

Let's say I have follow classes:

public class File { }
public class DB { }

public abstract class Validator<T>
{
    T obj;
}

public class FileValidator : Validator<File>
{
}

public class DbValidator : Validator<DB>
{
}

In code I would like to have a ref to abstract class and create certain implementation depends on some condition (like factory).

public class Program
{
    static Validator getValidator()
    {
        //some condition here
        return new FileValidator<File>();
    }

    public static void Main()
    {
        Validator v = getValidator();
    }
}

So, the compiler has a different opinion on this point

Using the generic type 'Validator' requires 1 type arguments

Is there any workaround in this case? Unfortunately, File and DB can't have common interface.

Upvotes: 0

Views: 1156

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You need a non-generic interface or abstract base-class:

public interface IValidator { ... }
public abstract class Validator<T> : IValidator
{

}

Now you can return IValidator from your method:

static IValidator getValidator()
{
    //some condition here
    return new FileValidator<File>();     
}

public static void Main()
{
    IValidator v = getValidator();
}

However be aware that there is no way for the compiler to infer the actual type, which is based upon a runtime-decision.

Apart from this your implementing classes should not be generic at all, only your abstract class should be:

public class FileValidator : Validator<File>
{
}

public class DbValidator : Validator<DB>
{
}

Upvotes: 3

Related Questions