I want to create a Validatable<T>
class which is similar in concept to Nullable<T>
. I have an IValidatable
interface used by many types, but if a type doesn't already implement this interface, I want to make it easy to put a wrapper around it and then use that wrapper to store validations errors.
I want to be able to cast back to the wrapped object, but the cast is failing even though I have an explicit operator set (although actually I'd prefer an implicit operator). Here's the definitions:
public interface IValidatable
{
bool IsValid { get; }
void Validate();
// (more validation-related methods here...)
}
public class Validatable<T> : IValidatable
where T : class
{
public Validatable(T obj)
{
Object = obj;
}
public T Object { get; private set; }
public bool IsValid { get; set; }
public void Validate()
{
}
public static implicit operator Validatable<T>(T other)
{
return new Validatable<T>(other);
}
public static explicit operator T(Validatable<T> other)
{
return other.Object;
}
}
public static class Validatable
{
public static IValidatable AsValidatable<T>(T obj)
where T: class
{
if (obj == null)
return null;
var already = obj as IValidatable;
return already ?? new Validatable<T>(obj);
}
}
public class Person // not IValidatable
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
But then if I try:
public void ConversionTest()
{
var person = new Person { FirstName = "Bob", LastName = "Smith" };
var validatable = Validatable.AsValidatable(person);
var cast = (Person)validatable; // FAILS here with InvalidCastException
}
Why is casting back to Person failing with an InvalidCastException?