Juan Lopez
Juan Lopez

Reputation: 361

Testing a generic IComparer

I'm trying to do a generic comparer and I'm not sure what is going wrong.

The comparer's code:

namespace Pract_02
{
    public class ComparerProperty<T> : IComparer<T>
    {
        private String attribute;
        public ComparerProperty(String text)
        {
            attribute = text;
        }
        public int Compare(T x, T y)
        {
            PropertyDescriptor property = GetProperty(attribute);
            IComparable propX = (IComparable)property.GetValue(x);
            IComparable propY = (IComparable)property.GetValue(y);
            return propX.CompareTo(propY);

        }

        private PropertyDescriptor GetProperty(string name)
        {
            T item = (T)Activator.CreateInstance(typeof(T));
            PropertyDescriptor propName = null;
            foreach (PropertyDescriptor propDesc in TypeDescriptor.GetProperties(item))
            {
                if (propDesc.Name.Contains(name)) propName = propDesc;
            }
            return propName;
        }
    }
}

And this is my test code:

public void TestComparer()
    {
        SortedSet<Vehicle> list = new SortedSet<Vehicle>(new ComparerProperty<Vehiculo>("NumWheels"));
        Car ca = new Car();
        Moto mo = new Moto();
        Tricycle tri = new Tricycle();
        list.Add(tri);
        list.Add(ca);
        list.Add(mo);
        IEnumerator<Vehiculo> en = list.GetEnumerator();
        en.MoveNext();
        Assert.AreEqual(en.Current, mo);
        en.MoveNext();
        Assert.AreEqual(en.Current, tri);
        en.MoveNext();
        Assert.AreEqual(en.Current, ca);


    }

The problem is when I test it I receive

"System.MissingMethodException: Cannot create an abstract class."

Here is the code for my Vehicle and Car classes:

public abstract class Vehicle
{
    public abstract int NumWheels
    {
        get;
    }
}

public class Car : Vehicle
{
    public override int NumWheels
    {
        get
        {
            return 4;
        }
    }
}

Upvotes: 0

Views: 402

Answers (1)

Jupin
Jupin

Reputation: 555

The MissingMethodException occurred while you were trying to create an instance from abstract class Vehicle. The problem is at line:

T item = (T)Activator.CreateInstance(typeof(T));

You can use following code to solve a problem

PropertyDescriptor propName = null;
foreach (PropertyDescriptor propDesc in TypeDescriptor.GetProperties(typeof(T)))
{
    if (propDesc.Name.Contains(name)) propName = propDesc;
}

return propName;

By the way, your approach has another several issues e.g.:

  • If you try compare non existing property you get NullReferenceException
  • If you try compare null property you get also NullReferenceException
  • If property is not IComparable you get InvalidCastException

Upvotes: 2

Related Questions