The VB.NET Extension on Nullable (Of T) object gives an error of type

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 assign a default value to an object with null values, and depending on whether it is null or not, it will give its own value or default value.

So, with a Date object, it will do this, which works, but I cannot get it to work with a common 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) 

Now the variable 'result' has the current DateTime.

When I try to use it with T, I get this as an error (which Visual Studio puts on T in Nullable (Of T): The type "T" must be a value type or a type argument limited to "structure" to be used with "Nullable" or a modifier with a null value of "?".

Thanks so much for any help!

Hello

+4
source share
3 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 sentences or not.

Update

In the comment below, only the first sentence is required:

 Public Function NValue(Of T as Structure)(ByVal value As Nullable(Of T), ByVal DefaultValue As T) As T 
+8
source

Your function is a little redundant, as this can be achieved with If :

 Dim nullval As Integer? = Nothing Dim value = If(nullval, 42) 

This is the same thing you wrote, namely:

 Dim value = If(nullval.HasValue, nullval.Value, 42) 

Its equivalent to the operator of zero coercion C # s ?? ( var value = nullval ?? 42; ).

+3
source

I was looking for the answer to this question and was happy with Andrew Cooper's decision, but I could not get it to work in practice, although it would compile. If I tried to call the extension method for the Nullable in question, I would not see my extension method in the list of available methods. If I called it directly, I would get the following error: "System.Nullable" does not satisfy the "Structure" constraint for a parameter of type "T". Only types with invalid Structure types are allowed. I found a possible explanation for this error here .

I used the getValueOrDefault () overload without any parameters, as it seemed to fulfill my original purpose. After some research, I am comfortable that GetValueOrDefault () is an adequate, if not preferred solution. In the case of FrieK, I decided to use the GetValueOrDefault () overload with the defaultValue parameter as the parameter.


+1
source

All Articles