C# TypeConverter long to enum type fails on ChangeType

2.2k views Asked by At

I'm fairly new to C# and .NET - I'm trying to get conversion to work from an integer to an enum. The conversion must be performable by ChangeType (outside of my demo below this is fixed as it's within the data binding framework) and from what I've read it should work with what I'm doing, but I get an exception and if I place breakpoints in the functions of my conversion class, nothing ever gets called.

Thanks in advance! -Matthew.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace csharptest
{
    class Program
    {

        [TypeConverter(typeof(UnitEnumConverter))]
        public enum LengthUnits
        {
            METRES,
            FEET
        };

        public class UnitEnumConverter : EnumConverter
        {
            public UnitEnumConverter(System.Type type)
                : base(type.GetType())
            {
            }

            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                if (sourceType == typeof(Int64)) return true;

                return base.CanConvertFrom(context, sourceType);
            }

            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
            {
                if (value is Int64)
                {
                    return (LengthUnits)(Int64)value;
                }
                return base.ConvertFrom(context, culture, value);
            }
        }

        static void Main(string[] args)
        {
            LengthUnits units = new LengthUnits();

            long x = 1;

            units = (LengthUnits)System.Convert.ChangeType(x, typeof(LengthUnits));

        }
    }
}
1

There are 1 answers

5
Mike Two On BEST ANSWER

Starting over from previous answers

Convert.ChangeType will not bother looking at the TypeConverter so that is no help. Using Reflector to look at Convert.ChangeType it just looks like it will not work. It has a static map of things that it can convert to. If it isn't in that list it will not try and convert. This is funny because a straight cast of an int or a long to your enum will just work.

I'm not sure which binding framework you are using but it seems odd that it would go down this route for enums.

I'm sorry I couldn't be of more help.