title: C# call Generic method dynamically
body: <p>Given the following Interfaces:</p>
  
  <pre><code>interface IEntity
  {
      int Id{get;}
  } 
  
  interface IPerson : IEntity
  {
      string Name{get;} 
      int Age{get;}
  }
  
  interface ITeacher : IPerson 
  {
      string StaffId{get;}
  }
  
  interface IStudent : IPerson 
  {
      string StudentId{get;}
      string Courses{get;}
  }
  
  interface IRepository
  {
      T Get&lt;T&gt;(int id) where T : IEntity
  }
  </code></pre>
  
  <p>I have the following classes in my namespace</p>
  
  <pre><code>public class EntityBase() : IEntity
  {
      int Id{get;set;}
  }
  public class Teacher : EntityBase, ITeacher{}
  public class Sudent : EntityBase, IStudent{}
  </code></pre>
  
  <p>Currently I am implementing this IRepository as follows:</p>
  
  <pre><code>class Repository: IRepository
  {
      IDataContext Context{get;set;}
  
      T Get&lt;T&gt;(int id) where T : EntityBase
      {
          if(typeof(T) == typeof(Teacher))
              return Context.Get&lt;ITeacher&gt;(id);
          if(typeof(T) == typeof(Sudent))
              return Context.Get&lt;ISudent&gt;(id);
          throw new Exception("Unknown Interface " + typeof(T).Name);
      }
  }
  </code></pre>
  
  <p>Is there a betterway of implementing this? Given that our Context has no knowledge of our data types (Teacher, Student), just its interfaces (ITeacher, IStudent).</p>
  
  <p>Can something like this work?</p>
  
  <pre><code>class Repository: IRepository
  {
      T Get&lt;T&gt;(int id) where T : EntityBase
      {
          var MyInterface = FindInterface&lt;T&gt;();
          return Context.Get&lt;MyInterface&gt;(id);
      }
  }
  </code></pre>