Advertisement
Guest User

Untitled

a guest
Sep 28th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.80 KB | None | 0 0
  1. class X
  2. {
  3.     public virtual void Blah() {
  4.         Console.WriteLine("X.Blah()");
  5.     }
  6. }
  7.  
  8. class Y : X
  9. {
  10.     public string message;
  11.  
  12.     public override void Blah() {
  13.         Console.WriteLine(message);
  14.     }
  15. }
  16.  
  17. interface HasBlah
  18. {
  19.     void Blah(object child);
  20. }
  21.  
  22. class Demo<T> : HasBlah
  23. {
  24.     public void Blah(T child) {
  25.         child.Blah();
  26.     }
  27.  
  28.     public override void Blah(object child) {
  29.         Blah(child as T); // This throws an exception if child can't be cast to T
  30.     }
  31. }
  32.  
  33. void ExampleFailure() {
  34.     X x = new X();
  35.     Y y = new Y();
  36.     y.message = "y.message";
  37.  
  38.     HasBlah demoX = new Demo<X>();
  39.     HasBlah demoY = new Demo<Y>();
  40.  
  41.     demoX.Blah(x); // outputs "X.Blah()"
  42.     demoY.Blah(y); // outputs "y.message"
  43.     demoY.Blah(x); // throws an exception
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement