views:

30

answers:

2

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

+2  A: 

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;).

Konrad Rudolph
I know it is, but I have to use it often so an extension would make it all shorter and more neat.
FrieK
@FrieK: if you know it why did you write it differently in your extension method? Apart from that, I don’t find your method neater than using `If`. Now, if you had used `[Or]` as the method name, this would allow writing `nullval.Or(42)`. Now *that* would indeed be neat.
Konrad Rudolph
Ohh I misunderstood, I'm sorry. You're right, just that If(..,..) would indeed be shorter, and Or is indeed a good idea, that would make it easier to read.
FrieK
+2  A: 

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
Andrew Cooper
Only the first `As Structure` clause is needed, the second one will cause a syntax error. Apart from that, this is correct.
Konrad Rudolph
I thought that might be the case. I haven't had need to use this yet myself, but I knew it was possible.
Andrew Cooper
Thank you very much! This did the trick. :)
FrieK