class A
{
}
class B : A
{
}
void method(A that is not a B argument) {}
void generic_method(generic_class<A that is not a B> generic_argument) {}
void params_method(params A that is not a B[] params_arguments) {}
Is there any syntactical way to do this? i realize that i could just do
if(argument is B)
throw new ArgumentException("argument cannot be a B", "argument");
at the beginning of the first method, and do that in a foreach for the second and third, but I'm wondering if there is some keyword or OOP concept that accomplishes this better.
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Can an object be a subclass of another object? A. Yes—as long as single inheritance is followed.
A superclass object is a subclass object. c. The class following the extends keyword in a class declaration is the direct superclass of the class being declared.
In the absence of any other explicit superclass, every class is implicitly a subclass of Object . Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object .
So it sounds like you're trying to express the opposite of a constraint such as:
var Foo<T>() where T : SomeClass
That would constrain T
to be SomeClass
or a subclass1... but you're trying to make it explicitly not a T
.
No, I'm afraid there's no such constraint in C#.
1 Well, modulo the assumption that SomeClass
is a class to start with; it could be an interface, with the meaning you probably expect.
No such constraint exists in C# because it's a bad idea, specifically its a violation of the Liskov substitution principle (one of the SOLID principles)
Substitutability is a principle in object-oriented programming. It states that, in a computer program, if
B
is a subtype ofA
, then objects of typeA
may be replaced with objects of typeB
(i.e., objects of typeB
may be substituted for objects of typeA
) without altering any of the desirable properties of that program
If your program explicitly rejects objects of type B
then that's clearly a violation of the LSP and a strong indication that you are doing polymorphism wrong - probably B
shouldn't inherit from A
in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With