I have a method which returns two values (HttpResponse and Generic object). Below is the code snippet.
In some condition I have to return one of the items as null. I tried the following condition but it didn't work.
internal sealed class OnlineHelper<T>
{
internal static Tuple<T, HttpStatusCode> GetRequest(arg1, arg2...)
{
....
if (webResponse.StatusCode == HttpStatusCode.OK)
{
return Tuple.Create(serializer.Deserialize<T>(response),
webResponse.StatusCode);
}
return Tuple.Create(null, webResponse.StatusCode); // Compiler error
return Tuple.Create(default(T), webResponse.StatusCode);
// ^- Throwing null reference exception.
}
}
You can use the simple constructor: new Tuple<T, HttpStatusCode> () or Tuple.Creare. The tricky part here is that you need to cast null to your generic type, so it should allow nulls. return new Tuple<T, HttpStatusCode> ( (T)null, webResponse.StatusCode)
That wont throw a NRE, probably the code using the tuple is. and what does the compile error tell you? something like cannot infer types from parameters ?? Yes, you can. If you do this it works: What you tried to was have the compiler determine the type for the null and it can't do that so you have to explicitly provide the generic types.
Several alternatives for returning null values include using null object reference types, a null object pattern, and a result type as the return type. Therefore, the recommendation is to return an empty value instead of a null to keep the code clean and error-free. Have you ever been in a situation where an application's state changes unexpectedly?
In most cases, a function will return NULL if any of its arguments are NULL (but there are exceptions). Many built-in functions can return NULL even if none of the arguments are NULL. In fact, that's the whole point of the NULLIF function.
Yes, you can. If you do this it works:
var tuple = Tuple.Create<string, int>(null, 42);
What you tried to was have the compiler determine the type for the null
and it can't do that so you have to explicitly provide the generic types.
So, in your case, try this:
return Tuple.Create<T, HttpStatusCode>(null, webResponse.StatusCode);
You would also need to add the generic class
constraint to your method to allow null
to be cast to T
.
internal static Tuple<T, HttpStatusCode> GetRequest(arg1, arg2...)
where T : class
You can use the simple constructor: new Tuple<T, HttpStatusCode>()
or Tuple.Creare
. The tricky part here is that you need to cast null to your generic type, so it should allow nulls.
Alter your class declaration to support nulls:
internal sealed class OnlineHelper<T> where T: class
And later cast or use default(T)
return new Tuple<T, HttpStatusCode>((T)null, webResponse.StatusCode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With