Skip to content

Make Generic Type allows you to create types with abstract classes when the constrant should block it #101962

@Faolan-Rad

Description

@Faolan-Rad

Description

You can create types with new() constraint which should block the use of abstract classes but it allows them any way though the use of the MakeGenericType and then you can instantiate them through activator

Reproduction Steps

public abstract class W { 
    /// This makes the bug happen
    public W()
    { }
}

public sealed class Trains<T> where T : W, new() { }

internal class Program
{
    static void Main(string[] args)
    { 
        //var e = new Trains<W>(); // This line has expected must be a none-abstract type 
        var e = Activator.CreateInstance(typeof(Trains<>)
            .MakeGenericType(typeof(W))); // This runs add creates the invalid type anyway
        Console.WriteLine(e?.ToString());
    }
}

Expected behavior

Probably for MakeGenericType to throw an invalid type exception

Actual behavior

It lets the type get created and it can be instated with the activator without a problem

Regression?

It happens from 6 - 8 did not test any more

Known Workarounds

You could add your own type check before hand

Configuration

.net 6 - 8

Other information

MakeGenericType probably just add a is abstract check for when it is a new() constraint

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-TypeSystem-coreclrin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions