Delphi implements keyword (or dynamic interface integration) (or introduction)
I guess that my next feature request for eXtensible C# (or idea at least) would be the ability to add methods (and by extension any kind of members...) to a class. By using an attribute we could add one or a set of methods to classes.
This could become even more useful if XC# provided us with the ability to define new interface implementations on classes. This would mimic the Delphi implements keword.
Here is a small explaination of what this keyword does in Delphi:
Dynamic aggregation of interfaces is not supported by the CLR, because it cannot be statically verified. In Delphi for .NET, all interfaces must be declared on the type. Dynamic aggregation is provided by the implements keyword, as the following code illustrates.
program Project1;
type
i = interface
procedure Wombat;
end;
TA = class(TInterfacedObject, i)
procedure Wombat;
end;
TC = class(TInterfacedObject, i)
fa: TA;
property a: TA read fa implements i;
end;
{ TA }
procedure TA.Wombat;
begin
end;
begin
end.
This is something that is really missing in .NET. In .NET, if you have a bunch of objects that must implement an interface, you have to implement every method of the interface in every object. In Delphi, you just have to implement the interface in one object (let's call it an interface helper), then say that all the objects that must implement that interface are using this interface helper.
With an XC# attribute, it could look like this:
interface IMyInterface
{
void method1();
}
class MyInterfaceHelper : IMyInterface
{
void method1()
{
// do something
}
}
[Implements(typeof(IMyInterface), typeof(MyInterfaceHelper))]
class MyClass1
{
}
[Implements(typeof(IMyInterface), typeof(MyInterfaceHelper))]
This way, the behavior of MyClass1 and MyClass2 objects are the same regarding the IMyTypeInterface, and we don't have to duplicate code or redeclare every method of the IMyInterface interface in every class.
Maybe there are existing ways to do this in .NET? I'd be curious to know how you solve this kind of situation...