Search code examples
c#.netgenerics

Operator '==' cannot be applied to same generic type


I'm not sure I understand the cause of this error or what to do about it.

I have a generic class.

public class RadioCommandCollection<T> : List<RadioCommand<T>> where T : struct, IComparable<T>
{
    /// <summary>
    /// Sets the value associated with the selected menu item to button.
    /// </summary>
    public void SetValue(T value)
    {
        foreach (RadioCommand<T> command in this)
        {
            command.SetIsSelected(command.Value == value);
        }
    }
}

And the line in the foreach block gives me an error:

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

Note that RadioCommand<T>.Value is of type T. It seems like I'm only defining T once here. I don't get the conflict.

I added the IComparable<T> constraint but that didn't help. Note that I'd like to restrict T to an enum, but that's not a valid constraint.


Solution

  • Simpliest way

    public class RadioCommandCollection<T> : List<RadioCommand<T>> where T : struct
    {
        /// <summary>
        /// Sets the value associated with the selected menu item to button.
        /// </summary>
        public void SetValue(T value)
        {
            foreach (RadioCommand<T> command in this)
            {
                command.SetIsSelected(command.Value.Equal(value));
            }
        }
    }
    

    Other way

    public class RadioCommandCollection<T> : List<RadioCommand<T>> where T : class
    {
        /// <summary>
        /// Sets the value associated with the selected menu item to button.
        /// </summary>
        public void SetValue(T value)
        {
            foreach (RadioCommand<T> command in this)
            {
                command.SetIsSelected(command.Value == value);
            }
        }
    }