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));
}
}
}