1

I've been heavily learning generic constraints the last week. While learning them more in depth, I became curious if it's possible to invert them in some way. The people I work with aren't sure that such a thing exists and my google searching has also come up with nothing.

The closest answer I got was to use struct instead of class, but while I can see why the person thought this was a decent answer and would work for most of the uses, it still doesn't answer if there is a way of inverting the constraint.

Does anyone else know if it's possible to invert a constraint?

e.g.

class myClass<T> where T: !class
{
}
Monofuse
  • 735
  • 6
  • 14

1 Answers1

4

No, there is no such syntax in C#.

From MSDN:

The following table lists the six types of constraints:

where T: struct The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types for more information. where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

where T : (base class name) The type argument must be or derive from the specified base class.

where T : (interface name) The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U The type argument supplied for T must be or derive from the argument supplied for U.

So there is no option to say where T is any type other than U

Think about it this way - suppose you had

class myClass<T> where T: !string
{
}

You know T is not a string, but you have no other indication of what T might be. So how do you code against it? These would all be valid delcarations:

var x1 = new myClass<int>();
var x2 = new myClass<object>();
var x3 = new myClass<DateTime>();
var x4 = new myClass<DataTable>();

What code could you have that applies to all of these types, but would be invalid for string?

Community
  • 1
  • 1
D Stanley
  • 149,601
  • 11
  • 178
  • 240