using System; namespace Chernobyl { /// /// Thrown when an instance of an improper type is provided to some code. /// public class InvalidTypeException : Exception { /// /// Initializes a new instance of the /// class whose is set to null. /// /// The error message that explains the reason for /// the exception. /// The instance that was of improper type. /// The type that /// was expected to be. public InvalidTypeException(string message, object instance, Type expectedType) : this(message, instance, expectedType, null) {} /// /// Initializes a new instance of the /// class. /// /// The error message that explains the reason for /// the exception. /// The instance that was of improper type. /// The type that /// was expected to be. /// The exception that is the cause of the /// current exception, or a null reference (Nothing in Visual Basic) if /// no inner exception is specified. public InvalidTypeException(string message, object instance, Type expectedType, Exception innerException) : base(message, innerException) { Instance = instance; } /// /// The instance that was of improper type. /// public object Instance { get; private set; } /// /// The type that was expected to be. /// public Type ExpectedType { get; private set; } } /// /// Extension and utility methods for and /// related types. /// public static class MethodExceptionExtensions { /// /// Casts the provided to /// and returns it. If it cannot be casted, an /// is thrown. /// /// The type to cast to. /// The instance that is to be casted. /// The casted . /// Thrown when the provided /// cannot be casted to . public static T Require(this object instance) where T : class { T castedInstance = instance as T; if (castedInstance == null) throw new InvalidTypeException( string.Format("'{0}' must be of type '{1}'.", instance, typeof(T)), instance, typeof(T)); return castedInstance; } } }