Is there a way to prevent extension methods from appearing for both derived and base types and limit them only to the base type?
My situation is a bit of a special case, but long story short, I have a scenario where it is safe to cast from a base entity to the derived entity and is also safe to cast from a List of derived entities to a List of base entities or vice versa. Since these cast’s would normally be unsafe, I am providing extension methods to do the casts so that developers using my library don’t have to remember which casts are safe and which are not.
The ToDerivedEntity extension method is implemented in relation to the BaseEntity, and while it doesn’t hurt anything to call ToDerivedEntity on a DerivedEntity, it would be nice, from a usability perspective, if I could prevent ToDerivedEntity from appearing on DerivedEntity and limit it only to the BaseEntity.
public class BaseEntity
{
}
public class DerivedEntity : BaseEntity
{
}
static class ExtensionMethods
{
// Should only show up on BaseEntity.
public static ToDerivedEntity(this BaseEntity source)
{
return (DerivedEntity)source;
}
}
No. You can’t do that. Extension methods apply to any derived type of the receiver. The best you can do is enforce such things dynamically (based on the runtime type of the object). i.e. throw an exception. But in this case that’s not appropriate. You want the method to be callable on an object of type derived.
More importantly, this is not something you want to do, from an API design perspective. Consider “ToString()”. It also exists on String.