MyBug18
MyBug18

Reputation: 2230

Understanding C# generic and upcasting

Please see following examples:

class A : ISomething
class B : ISomething
class C : ISomething

private void AcceptsISomething<T>(T input) where T : ISomething
{
    if (input is A)
    if (input is B)
    if (input is C)
}

private void AcceptsISomething(ISomething input)
{
    if (input is A)
    if (input is B)
    if (input is C)
}

What's the difference of functionality between above two examples?

I think there is no difference because both function ensures that input has implemented ISomething, and in both function input can be successfully pattern-matched to the types which implements ISomething.

But I also think that if there were really no difference, then there would be no reason for the lauguage feature where to exist.

Upvotes: 1

Views: 88

Answers (2)

marsze
marsze

Reputation: 17064

Your example is very simple, but in general there are a lot of things you can do with where only:

Multiple constraints

void AcceptsISomething<T>(T input) where T : ISomething, new()

Inheritance

class Base<T> where T : ISomething

class ChildA : Base<A>

Return value

private T Modify<T>(T input) where T : ISomething

var value = new A();
value = Modify(value); // vs (A)Modify(value)

Concrete type

private void AcceptsISomething<T>(T input) where T : ISomething
{
    Console.WriteLine(typeof(T));
}

A value = null;
AcceptsISomething(null); // prints "A" although argument is null

Upvotes: 2

Ronald Korze
Ronald Korze

Reputation: 828

Well in your example there actually is no difference, but the WHERE constraint for generics is indeed very useful. By adding a WHERE constraint to a generic function, you can ensure that the used type is derived (or is) the the type in the constraint. By this, you also can use functions of this type.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

Upvotes: 2

Related Questions