VB.NET Extension on Nullable(Of T) object, gives type error
The code I want to work:
<Extension()>
Public Function NValue(Of T)(ByVal value As Nullable(Of T), ByVal DefaultValue As T) As T
Return If(value.HasValue, value.Value, DefaultValue)
End Function
So basically what I want it to do, is to give along a default value to a nullable object, and depending on if it's null or not, it will give its own value or the default one.
So with a Date object, it would do this, which works, but I can't get it to work with the generic T:
<Extension()>
Public Function NValue(ByVal value As Date?, ByVal DefaultValue As Date) As Date
Return If(value.HasValue, value.Value, DefaultValue)
End Function
Dim test As Date? = Nothing
Dim result = test.NValue(DateTime.Now)
The variable 'result' now has the current DateTime.
开发者_如何学运维When I try it with T, I get this as error (which Visual Studio puts on the T in Nullable(Of T): Type 'T' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Thank you very much for any help!
Greetings
Try:
Public Function NValue(Of T as Structure)(ByVal value As Nullable(Of T as Structure), ByVal DefaultValue As T) As T
I'm not sure if you need both as Structure
clauses or not.
Update
Per the comment below, only the first clause is required:
Public Function NValue(Of T as Structure)(ByVal value As Nullable(Of T), ByVal DefaultValue As T) As T
Your function is a bit redundant because the same can be achieved by If
:
Dim nullval As Integer? = Nothing
Dim value = If(nullval, 42)
This is the same as what you’ve written, namely:
Dim value = If(nullval.HasValue, nullval.Value, 42)
It’s the equivalent to C#’s null coercion operator ??
(var value = nullval ?? 42;
).
I was looking for the answer to this question and was pleased with Andrew Cooper's solution, but I couldn't get it to work in practice, though it would compile. If I tried to invoke the extension method on the Nullable in question, I would not see my extension method in the list of available methods. If I called it directly, I would receive the following error "'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed." I found a possible explanation for this error here.
I used the overload of GetValueOrDefault() with no parameters, as it seemed to accomplish my initial goal. After some research, I am comfortable that GetValueOrDefault() is an adequate, if not preferable solution. In FrieK's case, I would elect to use the overload of GetValueOrDefault() with defaultValue as a parameter.
精彩评论