0

I am writing a method that takes a generic type and I am trying to create an instance of it.

public static class Grid
{
    public static T TestGeneric<T>()
        where T : new()
    {
        T Result = new T();
        return Result;
    }
}

However, this is returning null. My object inheritance is pretty complex and it would take me awhile to break it apart to see whether there is something there causing it. In general, what would cause the new T() function to return null?

William
  • 3,335
  • 9
  • 42
  • 74
  • Your code looks fine here. Are there any try..catch blocks? – Daniel A. White Jun 03 '14 at 15:44
  • 7
    Use the debugger. You'll probably find that this function *does not* return null and you misinterpreted something. – usr Jun 03 '14 at 15:45
  • 1
    This may seem like a silly question but have you debugged this method to see what the value of `Result` is? – David Pilkington Jun 03 '14 at 15:45
  • what about `default(T)`? – Troy Carlson Jun 03 '14 at 15:46
  • can you show how you are calling this method as well.. is the Grid Null reference this existing Stackoverflow Answer and try to follow it's example if you don't know how to use the debugger .http://stackoverflow.com/questions/13989093/how-to-initialize-generic-parameter-type-t – MethodMan Jun 03 '14 at 15:47
  • What type are you using to call the method? I can't seem to duplicate your results using, object, int, custom class with default constructor and without. – tinstaafl Jun 03 '14 at 16:24
  • @TroyCarlson No need to use default(T), he is using the new() constraint. –  Jun 03 '14 at 16:49
  • I am using a custom class. Yes, I have debugged it and literally the method new T() is returning a null value... – William Jun 03 '14 at 18:12
  • Is `T` equal to `int?` or some other nullable type?; `new T()` is translated to a call to `Activator.CreateInstance()` and that can return null (e.g. http://stackoverflow.com/questions/7137884/system-activator-createinstance-returning-null). – usr Jun 03 '14 at 19:24

0 Answers0