fork download
  1. public interface IInterface1 {};
  2. public interface IEtcetera {};
  3.  
  4. public struct CanUseThis : IEtcetera, IInterface1 {}
  5. public class OrThat : IEtcetera, IInterface1 {}
  6.  
  7. public class Foo
  8. {
  9. private IInterface1 _object; // just pick one
  10.  
  11. public void setObject<T>(T obj)
  12. where T : IInterface1, IEtcetera
  13. {
  14. // you now *know* that object supports all the interfaces
  15. // you don't need the compiler to remind you
  16. _object = obj;
  17. }
  18.  
  19. public void ExerciseObject()
  20. {
  21. // completely safe due to the constraints on setObject<T>
  22. IEtcetera itf = (IEtcetera) _object;
  23.  
  24. // ....
  25. }
  26. }
  27.  
  28. public class Program
  29. {
  30. public static void Main(string[] args)
  31. {
  32. var foo = new Foo();
  33.  
  34. foo.setObject(new CanUseThis());
  35. foo.ExerciseObject();
  36.  
  37. foo.setObject(new OrThat());
  38. foo.ExerciseObject();
  39. }
  40. }
  41.  
stdin
Standard input is empty
compilation info
prog.cs(22,19): warning CS0219: The variable `itf' is assigned but its value is never used
Compilation succeeded - 1 warning(s)
stdout
Standard output is empty