title: IServiceProvider with a restriction on the Type the user can ask the provider for
body: <p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.iserviceprovider?view=net-6.0" rel="nofollow noreferrer"><code>IServiceProvider</code></a> has a single method <a href="https://docs.microsoft.com/en-us/dotnet/api/system.iserviceprovider.getservice?view=net-6.0#system-iserviceprovider-getservice(system-type)" rel="nofollow noreferrer"><code>public object? GetService (Type serviceType)</code></a>.</p>
  <p>Is there a language construct to restrict the <code>Type serviceType</code> argument to only things that implement a certain <code>IMarker</code> interface (which has no methods, only serves as a marker for API discoverability).</p>
  <p>Kind of like this (but this obviously doesn't compile):</p>
  <pre class="lang-cs prettyprint-override"><code>public interface IMarker { }
  
  public class SvcProvider : IServiceProvider {
    public object? GetService(Type serviceType) where Type : IMarker {
      
    }
  }
  </code></pre>
  <hr />
  <p>I tried <a href="https://stackoverflow.com/questions/72412086/c-sharp-factory-constraints-on-return-type?noredirect=1#comment127922031_72412086">phrasing this question differently here</a>, but got into some trouble with people understanding what I was trying to achieve.</p>
  <hr />
  <h3>Updated code for comments discussion:</h3>
  <p>Same snippet of dotnetfiddle: <a href="https://dotnetfiddle.net/yXNq8K" rel="nofollow noreferrer">https://dotnetfiddle.net/yXNq8K</a></p>
  <pre class="lang-cs prettyprint-override"><code>public interface IMarker {}
  
  public class Impl1 : IMarker {}
  
  public class Program
  {
      //Compiles Ok
      public static T? GetServiceDefaultConstruct&lt;T&gt;() where T : IMarker, new() {
          return new T();
      }
      
      // Doesn't compile, says that T can be a non-nullable value type.
      public static T? GetServiceNull&lt;T&gt;() where T : IMarker {
          return null;
      }
      
      // Compiles Ok
      public static T? GetServiceNullExplicitConstraint&lt;T&gt;() where T : class,IMarker {
          return null;
      }
      
      // Doesn't compile: &quot;Can not convert Impl1 to T&quot;
      public static T? GetService&lt;T&gt;() where T : class,IMarker {
          if (typeof(T) == typeof(Impl1))
              return new Impl1();
          return null;
      }
  }
  </code></pre>