0

I have this Generic Method that always returns a nullReferenceException. I've taken all the unnecessary code out, and it still give me the exception.

    public T RetrieveInformationFromApi<T>(int Id) where T : IMovie
    {
        T result = default(T);

        result.Title = "test";
     }

The method can be called with three different classes that all have the attribute Title and the all implement the interface IMovie but the method still give me an exception. What am i doing wrong?

John Saunders
  • 157,405
  • 24
  • 229
  • 388
Peter
  • 699
  • 4
  • 7
  • 23

3 Answers3

5

You should add a constructor constraint on you T parameter so you can create a new instance.

public T RetrieveInformationFromApi<T>(int Id) where T : IMovie, new()
{
    T result = new T();

    result.Title = "test";
}
Johnbot
  • 2,139
  • 1
  • 25
  • 23
4

You're using default which returns null for reference types (and I'm guessing you're using a reference type.

From MSDN:

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types.

I'm not sure what you're trying to achieve but this way you will always get that exception for reference types.

Szymon
  • 41,313
  • 16
  • 90
  • 109
  • 1
    He will not "always" get the exception. When he calls that method with `T` being a `struct` (value type) implementing `IMovie`, then the setter of `result.Title` *will* be called. – Jeppe Stig Nielsen Nov 29 '13 at 22:52
  • @JeppeStigNielsen Very true, I edited the answer to make it correct. – Szymon Nov 29 '13 at 22:57
3

When the T is a reference type (class), the default (T) returns null, as it is the default value of all reference types.

Then obviously trying to access its property results in NullReferenceException

Honza Brestan
  • 9,621
  • 2
  • 32
  • 42