I have this class structure (simplified):
public class InducingMedium
{
public required string File { get; set; }
}
public class InducingVideo : InducingMedium {}
public class InducingAudio : InducingMedium {}
Now, I want to generically instantiate an instance of a specific type:
public abstract class BaseInducingTests<TMedium>
where TMedium : InducingMedium, new()
{
protected async Task<IEnumerable<TMedium>> CreateInducingMedia(IEnumerable<string> files)
{
return files.Select(file =>
{
// Do some processing...
return new TMedium
{
File = file,
};
});
}
}
public class InducingVideosTests : BaseInducingTests<InducingVideo>
{
}
But in the derived class I get an error:
'Namespace.InducingVideo' cannot satisfy the 'new()' constraint
on parameter 'TMedium' in the generic class 'Namespace.Tests.BaseInducingTests<TMedium>'
because 'Namespace.InducingVideo' has required members
Is there any way to fix this without introducing reflection?
I was really excited about required
members, which work pretty well with nullable types, but now I see this has its own caveats :(
SetsRequiredMembers
disables the compiler's checks that all required members are initialized when an object is created. Use it with caution.", one reason being - it does not even check if ctor actually does what is claimed (i.e. setsFile
in this case). – Abolition