Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 373
Rik De Peuter Avatar asked Dec 16 '22 20:12

Rik De Peuter


1 Answers

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
like image 188
Andrew Cooper Avatar answered Dec 29 '22 00:12

Andrew Cooper