0

I was going through the MSDN document for the Generic type constraint and I found the following paragraph.

You use the default constraint to specify that your derived class overrides the method without the constraint in your derived class, or explicit interface implementation. It's only valid on methods that override base methods, or explicit interface implementations:

public class D : B { // Without the "default" constraint, the compiler tries to override the first method in B public override void M<T>(T? item) where T : default { } } 

I couldnt understand the part of derived class overriding the method without the constraint. Can this please be explained with an elaborated example with the value needs to be passed for T in "M" method?

2
  • learn.microsoft.com/en-us/dotnet/csharp/language-reference/… Commented Oct 1, 2021 at 12:59
  • 2
    If you scroll a few paragraphs up the same document from which you are quoting, you will see the motivation for adding the default constraint: it lets you resolve the ambiguity between T? meaning Nullable<T> and T? meaning a reference object that allows null values. Commented Oct 1, 2021 at 13:07

1 Answer 1

3

It might be easier to understand if you try to do it. Let's say you have:

public abstract class BaseLogger { public void Log<T>(T? item) where T : struct { Console.WriteLine("I **cannot** be overriden!"); } public virtual void Log<T>(T? item) { Console.WriteLine("I **can** be overriden!"); } } 

Now, you have a child class, where you want to override the only virtual method:

public class Logger : BaseLogger { public override void Log<T>(T? item) { Console.WriteLine("I am overwriting my parent method!"); } } 

All good, right? Well, not exactly, no:

Compilation error: 'Logger.Log<T>(T?)': cannot override inherited member 'BaseLogger.Log<T>(T?)' because it is not marked virtual, abstract, or override Compilation error: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' 

As the document explains, the compiler cannot resolve the ambiguity between T? (a nullable reference type) and T? (the shorthand for Nullable<T>), so you need a way to specify the method that can be overriden. That's where the new default constraint becomes useful:

public class Logger : BaseLogger { public override void Log<T>(T? item) where T: default { Console.WriteLine("I am overwriting my parent method!"); } } 

Now it actually compiles. See it live: https://dotnetfiddle.net/vXgzWx

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.