C# 9 adds a whole list of new language features. Most people talk about the support for record types and improved pattern matching but one of the features I’m happy that is finally added to the language are covariant return types.
You are probably asking covariant return what?????
Let’s explain; with return type covariance, you can override a base class method that has a less-specific type with one that returns a more specific type.
An example, before C#9 you would have to return the base type from the inherited class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EmployeeBuilder:PersonBuilder | |
{ | |
//Our return type remains Person | |
public override Person Create() | |
{ | |
return new Employee(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PersonBuilder | |
{ | |
public virtual Person Create() | |
{ | |
return new Person(); | |
} | |
} |
In C# 9, you can do the following:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EmployeeBuilder:PersonBuilder | |
{ | |
public override Employee Create() | |
{ | |
return new Employee(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PersonBuilder | |
{ | |
public virtual Person Create() | |
{ | |
return new Person(); | |
} | |
} |