eidylon
eidylon

Reputation: 7238

Can I define a generic that can take several possible value types? (VB.NET)

Is there any way to define a Generic in VB.NET which will accept only Singles or Doubles?

I tried the following things, based on what I've found online, but none compile:

Dim target As Nullable(Of {Single, Double})  
Dim target As Nullable(Of T As {Single, Double})
Dim target As Nullable(Of T {Single, Double})
Dim target As Nullable(Of Single, Double)  
Dim target As Nullable(Of T As Single, Double)

I want to specify that target can either be a Single? or a Double? only.

Upvotes: 1

Views: 408

Answers (1)

Jodrell
Jodrell

Reputation: 35746

Public Class NullableFloat(Of T As {Double, Single}) is the right syntax, see here under constraints.

However, this statement specifies that the generic type T must implement both Double and Single, not either. Since .Net primitives are sealed and there is no inheritance relationship between Double and Single there is no way that T could ever satisfy both constraints.

Since no .Net type can be both a Double and a Single you could make some complex type called NullableFloat with one Value property of Double type but with setters that take Double or Single but, why not just use Nullable(Of Double).

Upvotes: 3

Related Questions