On C# 3.0 and .NET 3.5, imagine there’s an interface:
public interface INameable { string Name {get;} }
and many immutable classes that implement the interface.
I would like to have a single extension method
public static T Rename<T>(this T obj) where T : INameable { ... }
that returns a wrapped instance of the original object with just the name changed and all other property reads and method calls routed to the original object.
How to get a generic wrapper class for this, without implementing it for all INameable implementing types? Do you think that’s possible?
No, this isn’t possible, unless
Tis constrained to be an interface or to be a class with all members virtual, and this constraint isn’t possible to specify at compile time (though you could write a runtime check if you’re happy with that approach).The reason you cannot do it for arbitrary types is that if you take an object of type
Tthen you must return an object that is assignable toT. If I pass an object that looks as follows……then there is no way you can create another type that is assignable to
SomeClass. Not usingReflection.Emitor any other method, because the type is sealed.However, if you’re happy with the restrictions that I’ve mentioned then you could use something like the Castle DynamicProxy framework to create a type that proxies the passed in object and intercepts the calls to either forward or re-implement as appropriate.