Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you cast T to a class to match a "where T : class" constraint?

I'm running into a generics issue while working on a generic Dependency Injection handler (a base Service Locator).

Edit 1 (for clarity)

Okay so I'm actually using SimpleInjector as a DI resolver and it has the class constraint on it's GetInstance method, so here is some more complete code:

  public T GetInstance<T>() where T : class
  {
     try
     {
        // works
        return _container.GetInstance<T>();
     }
     catch( ActivationException aEx )
     {
        return default( T );
     }
  }

  public T GetInstance<T>()
  {
     try
     {
        if( typeof( T ).IsClass )
        {
           // does not work, T is not a reference type
           return _container.GetInstance<T>();
        }
     }
     catch( ActivationException aEx )
     {
        return default( T );
     }
  }

Edit 2 - final code since it looks strange in comments:

  public T GetInstance<T>()
  {
     try
     {
        if( typeof( T ).IsClass )
        {
           return (T) _container.GetInstance(typeof(T));
        }
     }
     catch( ActivationException aEx )
     {
        return default( T );
     }
  }
like image 983
Laurence Avatar asked Nov 03 '22 17:11

Laurence


1 Answers

You can use one more helper method? please find test class below

public class Test
{
  public T GetInstance<T>() where T : class
  {
    return (T)GetInstance(typeof(T));
  }

  private object GetInstance(Type type) 
  {
     return Activator.CreateInstance(type);
  }

  public T GetEvenMoreGenericInstance<T>()
  {
     if( !typeof( T ).IsValueType )
     {
        return (T)GetInstance(typeof(T));
     }
     return default( T );
  }
}
like image 114
user854301 Avatar answered Nov 12 '22 13:11

user854301