Interface, Compile Error
Hi All,
If I have an usercontrol UC that makes calls to many function declared by interface IY, is there a way that I can make the compiler throws a compiling error if any usercontrol inherits from my usercontrol UC but does not implement interface IY.
I surely can throw an exception error at runtime. But I think it would be pretty good if I can make the compiler throw an exception at compling time instead. This would be a very nice feature to any enterprise organization.
Thanks
[491 byte] By [
DavidN.] at [2007-12-16]
When implementing the interface on UC, simply declare the implemented methods as abstract. That will force users to implement them. The derived control will not compile without implementing all abstract methods (unless the derived control is itself abstract.)
public interface IY {
void SomeMethod();
}
public abstract class UC : UserControl, IY {
public abstract void SomeMethod();
}
public class DerivedUC : UC {
public override void SomeMethod() {
// implementation goes here
}
}
However, I just realize that I already done some thing similar...
public interface IY {
void SomeMethod();
}
public class UC : UserControl, IY {
public virtual void SomeMethod(){} // do nothing
}
public class DerivedUC : UC {
public override void SomeMethod() {
// implementation goes here
}
}
The different is that class UC still can be used directly (which is kind of bad).
It would be nice if we can have a compiler directive like this:
public interface IY {
void SomeMethod();
}
[DeriveInterfaceRequire(IY, IX,...)] // I make this up
public class UC : UserControl
{
}
The [DeriveInterfaceRequire(IY,IX)] tells the compiler to generate error if any derived class of UC that does not implement IY, IX.
That way, if I have 50 interface functions for IY, I don't have to type (declare) them insite class UC. (and I still can use UC directly...:-))
Any way, it's just a thought. Probably not a good thought, though.
Thanks.