Home > Back-end >  Is it possible to restrict the Type passed to struct by the parent class?
Is it possible to restrict the Type passed to struct by the parent class?

Time:12-04

I would like to have a compile error except for the Type of a certain parent class. If you know of such a possibility, please let me know.

using System;

class Program
{
    static void Main(string[] args)
    {
        var objectA = new TypeReference(typeof(TargetSubClass));
        // I want to make a compile error if the parent class of Type is not TargetClass.
        var objectB = new TypeReference(typeof(NotTargetClass));
    }
}

public readonly struct TypeReference
{
    public readonly string TypeName;
    public readonly Type Type;
    
    public TypeReference(Type type)
    {
        Type = type;
        TypeName = Type.FullName;
    }
}

public class TargetClass{}
public class TargetSubClass : TargetClass{}
public class NotTargetClass{}

If it is run time, I can just throw a throw, but I want to make it a compile error like generic's where.

using System;

public readonly struct TypeReference
{
    public readonly string TypeName;
    public readonly Type Type;
    
    public TypeReference(Type type)
    {
        // confirmation of Type
        if (!typeof(TargetClass).IsAssignableFrom(type))
        {
            throw new ArgumentException("Type is not a TargetClass.");
        }
        Type = type;
        TypeName = Type.FullName;
    }
}

CodePudding user response:

You could create a generic factory method with appropriate constraint:

public readonly struct TypeReference
{
    public readonly string TypeName;
    public readonly Type Type;
    
    private TypeReference(Type type)
    {
        Type = type;
        TypeName = Type.FullName;
    }
    
    public static TypeReference Create<T>() where T : TargetClass
    {
        return new TypeReference(typeof(T));
    }
}
var objectA = TypeReference.Create<TargetSubClass>();
// this produces a compile error
var objectB = TypeReference.Create<NotTargetClass>();
  •  Tags:  
  • c#
  • Related