I’m having a problem instantiating an anonymous type in my code.
For some reason, TResponse response = default(TResponse); returns null, even though TResponse has a constructor for it.
Am I being dumb?!
Class:
public class MyClass
{
public MyResponse GetResponse(MyRequest request)
{
return Service<MyRequest, MyResponse>.MakeRequest(
request,
delegate() {
return AnotherService.GetRequest(request);
}
);
}
}
Service class
public static class Service<TRequest, TResponse>
where TRequest : IRequest
where TResponse : IResponse
{
public delegate TResponse UseDelegate();
public TResponse MakeRequest(TRequest request, UseDelegate codeBlock)
{
TResponse response = default(TResponse); // <-- Returns nulll
response = codeBlock();
return response;
}
}
As Brandon has said,
defaultreturnsnullfor any reference type.However, I don’t see why you’re using it at all – the value you’ve assigned will be overwritten by the return value of
codeBlock()anyway. In other words, you can change your MakeRequest method to just:or even:
I’m assuming that in reality there’s some more code there… but if you really want to call a parameterless constructor, you can constrain TResponse with:
and then use:
That way you’ll get a compile-time guarantee that
TResponsehas a parameterless constructor; just usingActivator.CreateInstance(typeof(TResponse))without a constraint onTResponsewould work, but would delay finding out about the problem where you tried to use response type which didn’t have a parameterless constructor.Furthermore, I don’t see any anonymous types in your code – the only way an anonymous type would have a parameterless constructor would be if you used:
which would be somewhat pointless.