System.ComponentModel.EnumConverter.ConvertTo C# (CSharp) Method

ConvertTo() private method

private ConvertTo ( ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType ) : object
context ITypeDescriptorContext
culture System.Globalization.CultureInfo
value object
destinationType System.Type
return object
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
            if (destinationType == null) {
                throw new ArgumentNullException("destinationType");
            }

            if (destinationType == typeof(string) && value != null) {
                // Raise an argument exception if the value isn't defined and if
                // the enum isn't a flags style.
                //
                Type underlyingType = Enum.GetUnderlyingType(type);
                if (value is IConvertible && value.GetType() != underlyingType) {
                    value = ((IConvertible)value).ToType(underlyingType, culture);
                }
                if (!type.IsDefined(typeof(FlagsAttribute), false) && !Enum.IsDefined(type, value)) {
                    throw new ArgumentException(SR.GetString(SR.EnumConverterInvalidValue, value.ToString(), type.Name));
                }
                
                return Enum.Format(type, value, "G");
            }
            if (destinationType == typeof(InstanceDescriptor) && value != null) {
                string enumName = ConvertToInvariantString(context, value);
                
                if (type.IsDefined(typeof(FlagsAttribute), false) && enumName.IndexOf(',') != -1) {
                    // This is a flags enum, and there is no one flag
                    // that covers the value.  Instead, convert the
                    // value to the underlying type and invoke
                    // a ToObject call on enum.
                    //
                    Type underlyingType = Enum.GetUnderlyingType(type);
                    if (value is IConvertible) {
                        object convertedValue = ((IConvertible)value).ToType(underlyingType, culture);
                        
                        MethodInfo method = typeof(Enum).GetMethod("ToObject", new Type[] {typeof(Type), underlyingType});
                        if (method != null) {
                            return new InstanceDescriptor(method, new object[] {type, convertedValue});
                        }
                    }
                }
                else {
                    FieldInfo info = type.GetField(enumName);
                    if (info != null) {
                        return new InstanceDescriptor(info, null);
                    }
                }
            }
            if (destinationType == typeof(Enum[]) && value != null) {
                if (type.IsDefined(typeof(FlagsAttribute), false)) {
                    List<Enum> flagValues = new List<Enum>();

                    Array objValues = Enum.GetValues(type);
                    long[] ulValues = new long[objValues.Length];
                    for(int idx = 0; idx < objValues.Length; idx++) {
                        ulValues[idx] = Convert.ToInt64((Enum)objValues.GetValue(idx), culture);
                    }

                    long longValue = Convert.ToInt64((Enum)value, culture);
                    bool valueFound = true;
                    while(valueFound) {
                        valueFound = false;
                        foreach(long ul in ulValues) {
                            if ((ul != 0 && (ul & longValue) == ul) || ul == longValue) {
                                flagValues.Add((Enum)Enum.ToObject(type, ul));
                                valueFound = true;
                                longValue &= ~ul;
                                break;
                            }
                        }

                        if (longValue == 0) {
                            break;
                        }
                    }

                    if (!valueFound && longValue != 0) {
                        flagValues.Add((Enum)Enum.ToObject(type, longValue));
                    }

                    return flagValues.ToArray();
                }
                else {
                    return new Enum[] {(Enum)Enum.ToObject(type, value)};
                }
            }
            
            return base.ConvertTo(context, culture, value, destinationType);
        }

Usage Example

Example #1
0
		public void ConvertTo_String ()
		{
			EnumConverter converter = new EnumConverter (typeof (E));

			Assert.AreEqual ("Bb", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, E.Bb,
				typeof (string)), "#A1");
			Assert.AreEqual ("Dd", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, 3,
				typeof (string)), "#A2");
			Assert.AreEqual (string.Empty, converter.ConvertTo (
				null, CultureInfo.InvariantCulture, null,
				typeof (string)), "#A3");
			Assert.AreEqual ("Cc", converter.ConvertTo (
				null, CultureInfo.InvariantCulture, (E) 2,
				typeof (string)), "#A4");
			Assert.AreEqual ("Cc", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, E2.Bb,
				typeof (string)), "#A5");
			Assert.AreEqual ("Dd", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, E.Bb | E.Dd,
				typeof (string)), "#A6");

			try {
				converter.ConvertTo (null, CultureInfo.InvariantCulture,
					(E) 666, typeof (string));
				Assert.Fail ("#B1");
			} catch (ArgumentException ex) {
				// The value '666' is not a valid value for the enum 'E'
				Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
				Assert.IsNull (ex.InnerException, "#B3");
				Assert.IsNotNull (ex.Message, "#B4");
				Assert.IsTrue (ex.Message.IndexOf ("'666'") != -1, "#B5");
				Assert.IsTrue (ex.Message.IndexOf ("'E'") != -1, "#B6");
				Assert.IsNull (ex.ParamName, "#B7");
			}

			try {
				converter.ConvertTo (null, CultureInfo.InvariantCulture,
					"Cc", typeof (string));
				Assert.Fail ("#C1");
			} catch (FormatException ex) {
				// Input string was not in a correct format
				Assert.AreEqual (typeof (FormatException), ex.GetType (), "#C2");
				Assert.IsNull (ex.InnerException, "#C3");
				Assert.IsNotNull (ex.Message, "#C4");
			}


			converter = new EnumConverter (typeof (E2));

			Assert.AreEqual ("Bb", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, E2.Bb,
				typeof (string)), "#B1");
			Assert.AreEqual ("Aa, Bb", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, 3,
				typeof (string)), "#B2");
			Assert.AreEqual (string.Empty, converter.ConvertTo (
				null, CultureInfo.InvariantCulture, null,
				typeof (string)), "#B3");
			Assert.AreEqual ("Bb", converter.ConvertTo (
				null, CultureInfo.InvariantCulture, (E2) 2,
				typeof (string)), "#B4");
			Assert.AreEqual ("Aa, Bb", converter.ConvertTo (
				null, CultureInfo.InvariantCulture, E.Dd,
				typeof (string)), "#B5");
			Assert.AreEqual ("Bb, Dd", converter.ConvertTo (null,
				CultureInfo.InvariantCulture, E2.Bb | E2.Dd,
				typeof (string)), "#B6");
		}
All Usage Examples Of System.ComponentModel.EnumConverter::ConvertTo