Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic Type Parameter Sharing across classes

Suppose you have the following Generic class heirarchy:

public abstract class GenericBase<T>
{
    T SomeProperty{ get; set; }
}

public class Foo<T>
{
    T SomeProperty{ get; set; }
}

public abstract class GenericChild<T> : GenericBase<T>
{
    // ...

    public bool DoSomething(Foo<T> foo)
    {
        // This is invalid:
        return SomeProperty == foo.SomeProperty;
    }
}

The equality check in the DoSomething method won't compile. It produces the following error:

Operator '==' cannot be applied to operands of type 'T' and 'T'

If it's releveant, these classes are in separate files. What's the best workaround to allow this kind of equality comparison? Is there some kind of pattern or something to allow this in C#?

Update:

A few of the answers suggest using a:

where T : SomeClass

Unfortunately, very often T will be a primitive type.

like image 840
Didaxis Avatar asked Jun 03 '26 20:06

Didaxis


1 Answers

== is not generically applicable for all types. It can only be used if T is constrained to a type that supports it, such as where T : class. However, you would probably be better served using the Equals method.

return SomeProperty.Equals(foo.SomeProperty);

With the applicable null checking applied.

like image 64
Anthony Pegram Avatar answered Jun 06 '26 08:06

Anthony Pegram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!