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
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