title: How to write an extension method to return the type being used?
body: <p>I have an extension method that allows a user to turn off lazy loading.</p>
  
  <pre><code>public static IBaseEntityService&lt;TEntity, TPrimaryKey&gt; EnableLazyLoading&lt;TEntity, TPrimaryKey&gt;(
          this IBaseEntityService&lt;TEntity, TPrimaryKey&gt; baseService,
          bool enabled)  
          where TEntity :Entity&lt;TPrimaryKey&gt; where TPrimaryKey : struct
      {
          baseService.UnitOfWork.EnableLazyLoading(enabled);
          baseService.UnitOfWork.EnableProxyCreation(enabled);
          var type = baseService.GetType().;
          return (type)baseService;
      }
  </code></pre>
  
  <p>Here is a sample of the base interface:</p>
  
  <pre><code> public interface IBaseEntityService&lt;TEntity,TPrimaryKey&gt; : 
      IBaseService&lt;TEntity, TPrimaryKey&gt; 
      where TEntity: Entity&lt;TPrimaryKey&gt; where TPrimaryKey : struct
  {
  
      TEntity FindByTenantId(Guid tenantId);
     IBaseEntitySpecification&lt;TEntity,TPrimaryKey&gt; Specification { get; } 
  }
  </code></pre>
  
  <p>Let's say I have this service that implements the <code>IBaseEntityService&lt;TEntity,TPrimaryKey&gt;</code> interface:</p>
  
  <pre><code>public IUserService: IBaseEntityService&lt;User,int&gt;
  {
        User FindByUserName(string username);
  }
  </code></pre>
  
  <p>Here is what I want to achieve:</p>
  
  <pre><code>var user = _userService.EnableLazyLoading(false).FindByUserName("someUsername");
  </code></pre>
  
  <p>As you can see in my example after the <code>EnableLazyLoading(false)</code> I can get to the <code>FindByUserName</code> method. Currently, since it only returns an IBaseEntityService I do not have that option. </p>
  
  <p>I want to ensure the extension method knows to return the <code>IUserService</code> since it implements the <code>IBaseEntityService</code>. I know it would have to cast it at some point and I want to avoid having to write a specific implementation of that same <code>EnableLazyLoading</code> method for the <code>IUserService</code></p>
  
  <p>I thought of something like this, but it seems like I could do something without having to implicitly call a Cast method:</p>
  
  <pre><code>public static TEntityService Cast&lt;TEntity, TPrimaryKey, TEntityService&gt;(
              this IBaseEntityService&lt;TEntity, TPrimaryKey&gt; baseEntityService)
              where TEntity : Entity&lt;TPrimaryKey&gt;
              where TPrimaryKey : struct
              where TEntityService : IBaseEntityService&lt;TEntity, TPrimaryKey&gt;
          {
              return (TEntityService) baseEntityService;
          }
  </code></pre>
  
  <p>So it might work like this:</p>
  
  <pre><code>var user = _userService.EnableLazyLoading(false).Cast&lt;IUserService&gt;().FindByUserName("someUsername");
  </code></pre>