/// <summary> /// Returns an object of the specified type and whose value is equivalent to the specified object. /// </summary> /// <param name="value">The object to convert the underlying type.</param> /// <param name="conversionType">The <see cref="Type"/> of object to return.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <returns>An object whose type is <paramref name="conversionType"/> and whose value is equivalent to <paramref name="value"/>.</returns> /// <remarks>What differs from the <see cref="Convert.ChangeType(object,System.Type)"/> is, that this converter supports generics and enums. Failover uses <see cref="TypeDescriptor"/>.</remarks> public static object ChangeType(object value, Type conversionType, IFormatProvider provider) { Validator.ThrowIfNull(conversionType, nameof(conversionType)); if (value == null) { return(null); } try { bool isEnum = conversionType.GetTypeInfo().IsEnum; bool isNullable = TypeUtility.IsNullable(conversionType); return(Convert.ChangeType(isEnum ? Enum.Parse(conversionType, value.ToString()) : value, isNullable ? Nullable.GetUnderlyingType(conversionType) : conversionType, provider)); } catch (Exception first) { try { return(TypeDescriptor.GetConverter(conversionType).ConvertFrom(value)); } catch (Exception second) { throw new AggregateException(first, second); } } }
/// <summary> /// Determines whether the specified source is a nullable <see cref="ValueType"/>. /// </summary> /// <typeparam name="T">The type of the <paramref name="source"/> of <typeparamref name="T"/>.</typeparam> /// <param name="source">The source type to check for nullable <see cref="ValueType"/>.</param> /// <returns> /// <c>true</c> if the specified source is nullable; otherwise, <c>false</c>. /// </returns> public static bool IsNullable<T>(this T source) { return TypeUtility.IsNullable(source); }
/// <summary> /// Determines whether the specified source is a nullable <see cref="ValueType"/>. /// </summary> /// <typeparam name="T">The type of the <paramref name="source"/> of <typeparamref name="T"/>.</typeparam> /// <param name="source">The source type to check for nullable <see cref="ValueType"/>.</param> /// <returns> /// <c>true</c> if the specified source is nullable; otherwise, <c>false</c>. /// </returns> public static bool IsNullable<T>(this T? source) where T : struct { return TypeUtility.IsNullable(source); }
/// <summary> /// Determines whether the specified source is a nullable <see cref="ValueType"/>. /// </summary> /// <param name="source">The source type to check for nullable <see cref="ValueType"/>.</param> /// <returns> /// <c>true</c> if the specified source is nullable; otherwise, <c>false</c>. /// </returns> public static bool IsNullable(this Type source) { return(TypeUtility.IsNullable(source)); }