Here are the classes and interfaces I have:
public interface Baz {
void someMethod();
}
public interface Foo {
void someMethod();
}
public class Bar : Foo {
void Foo.someMethod(){}
}
Question 1) Is it possible to remove Foo interface from a Bar object, or add a Baz interface to a Bar object during runtime possible?
If yes, can I have a short code sample on how it is done?
If no, kindly proceed to question 2 and 3.
Question 2) Why does C# not give a compile error when casting an object to an interface that it does not implement? If you answer to question 1 is no, mybar would never be a Baz, so why is there no compiler error?
void myFunction(){
Bar mybar = new Bar();
(mybar as Baz).someMethod();
}
Question 3) Why doesn't C# allow me to call someMethod from a Bar object without casting to Foo, even if it knows that someMethod is not ambiguous?
void myFunction(){
Bar mybar = new Bar();
mybar.someMethod();//doesn't work
mybar.Foo.someMethod();//doesn't work (C# could do this and give a compile error if Bar has a property or public variable with the same name as an interface that it implements to allow for this syntax)
(mybar as Foo).someMethod();//works even though someMethod is not ambiguous.
//The problem with this is that the keyword "as" has an option to return null, which I want to be very assured will never be the case.
}