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]
# 1

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
}
}

JamesKovacs at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 2

Hi James,

Thanks for code sample. It works beautifully.

DavidN. at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 3
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.

DavidN. at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 4
Glad I could help. Don't forget to "Mark as correct answer" for the correct solution on questions that you post. It helps others quickly search for posts with answers to them. See the following for details:

http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=1190

JamesKovacs at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...

.NET Development

Site Classified