New in .NET 7 (9): Overloading of operators in interfaces from C# 11.0
Since the first version of C#, the programming language has allowed operator overloading. C# 11.0 introduces the ability to define an operator overload in an interface to provide a default or commonality across implementations. Only since C# is 11.0 static abstract
allowed in interfaces.
dr Holger Schwichtenberg is Chief Technology Expert at MAXIMAGO, which offers innovation and experience-driven software development, including in highly critical safety-related areas. He is also head of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with advice and training in the development and operation of software with 38 renowned experts.
An interface with an overloaded operator might look like this:
namespace de.WWWings;
public interface IFlug<TSelf>
where TSelf : IFlug<TSelf>
{
string AbflugOrt { get; set; }
double Auslastung { get; }
DateTime Datum { get; set; }
long FlugNr { get; set; }
short FreiePlaetze { get; set; }
bool Nichtraucherflug { get; set; }
short Plaetze { get; set; }
string Route { get; }
string ZielOrt { get; set; }
public static abstract Flug operator
+(TSelf flug, de.WWWings.PassagierSystem.Passagier pass);
}
One or the other will ask why the interface has to be generic. The reason for this is simple: you end up wanting one Flug
-Object simply with +
can add up to a passenger. Without the generic implementation you could only have a variable of type IFlug
add to the passenger.
Finally, the implementation of the class still needs the interface implementation : IFlug<Flug>
:
namespace de.WWWings
{
public partial class Flug : IFlug<Flug>
{
…
/// <summary>
/// Operatorüberladung fuer die Buchung eines Flugs
/// durch Addition eines Flug- und eines Passagier-Objekts.
/// </summary>
/// <param name="flug">Flugobjekt</param>
/// <param name="pass">Passagierobjekt</param>
/// <returns>Flugobjekt mit hinzugefügten Passagier</returns>
public static Flug operator +(Flug flug,
PassagierSystem.Passagier pass)
{
pass.Buchen(flug);
return flug;
}
}
}
(rm)