Generic Constraints And Type Parameters Mess

Posted by Dummy01 on Stack Overflow See other posts from Stack Overflow or by Dummy01
Published on 2010-12-31T08:46:02Z Indexed on 2010/12/31 8:54 UTC
Read the original article Hit count: 188

Filed under:
|
|

Hi everyone,

I have the following base abstract class defined as:

public abstract class BaseObject<T> : IComparable, IComparable<T>, IEquatable<T> {}

I also have an interface defined as:

public interface ICode<T> where T : struct
{
    T Code { get; }
}

Now I want to derive a class that is inherited from BaseObject<T> and includes interface ICode<T>.

I tried to define it like that:

public class DerivedObject<T, U> : BaseObject<T>, ICode<U> where T : DerivedObject<T, U> where U : struct
{

    public DerivedObject(U code)
    {
        Code = code;
    }

    // From BaseObject
    protected override int InstanceCompareTo(T obj)
    {
        return Code.CompareTo(obj.Code);
    }

    // From BaseObject
    protected override bool InstanceEquals(T obj)
    {
        return Code.Equals(obj.Code);
    }

    // From ICode
    U _Code;

    public U Code 
    { 
        get { return _Code; }
        protected set { _Code = value; }
    }
}

The only error that comes from the compiler is for Code.CompareTo(obj.Code) with the message:

'U' does not contain a definition for 'CompareTo' and no extension method 'CompareTo' accepting a first argument of type 'U' could be found.

But U is a value type and should know CompareTo.

Have you any idea what I am doing wrong, or if I do all wrong?

My final aim is to derive classes such these:

    public class Account : DerivedObject<Account, int>
    public class ItemGroup : DerivedObject<ItemGroup, string>

Big Thanks In Advance!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET