Allowing new() generic constraint to have some required members if the derived class has no extra required members #7712
Replies: 3 comments 2 replies
-
You cannot know if the inheritance tree of a type is complete at compile-time. Assemblies may be dynamically loaded at runtime. So checking for this is not possible... I think... |
Beta Was this translation helpful? Give feedback.
-
Unless you don't have control over the type, you could use a static abstract method on an interface, have your type implement the interface, and use the interface as a constraint instead of the public interface INew<T> where T : INew<T>
{
static abstract T New();
}
public class MyClass : INew<MyClass>
{
public required string MyProperty { get; init; }
public static MyClass New()
{
return new MyClass() { MyProperty = "<DefaultValue>" };
}
}
public void DoThingWithNew<T>()
where T : INew<T>
{
var obj = T.New();
//... do whatever you need to do with obj
} |
Beta Was this translation helpful? Give feedback.
-
For reference, the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Currently, if you try to create a generic constraint with a type that has required properties, you cannot use the new() constraint in the where clause. Consider the following definition:
If you try to use the generic method as follows:
DerivedWithNoNewRequiredMembers _DoSomething<SomeDerivedWithNoNewRequiredMembers>();
...it will generate a compile-time error message along the lines of...
'XXXX' cannot satisfy the new() constraint on parameter 'YYYY' in the generic type or method 'ZZZZ' because 'ZZZZ' has required members.
That seems like overkill. I understand not being able to new a type via a default constructor if a derived type is passed as TResponse which has additional required members. The generic method won't know anything about those additional required members., so it can't properly "new" up the TResponse using the default constructor . However, given that generic constraints are validated at compile time, the compiler can detect if the derived class has no additional required members.
In such cases, the generic method has all the information it needs to populate the required members safely using the required properties in scope in the base class.
Could we not loosen this "required" member rule for the constraint in this case?
Beta Was this translation helpful? Give feedback.
All reactions