A
Andrew Ducker
I have a class "Validator" which can be cast to a Control. The code:
ValidTextBox t = (ValidTextBox)v;
works just fine.
However, because v doesn't descend from t, I can't use "is" or "as". I
did want a safe way of casting though - so I tried the following code:
public static T ConvertClass<T>(Validator myValidator) where T :
Control
{
T convertedObject;
try
{
convertedObject = (T)myValidator;
return convertedObject;
}
catch
{
return default(T);
}
}
and that worked fine. So I thought I'd make it more generic - no
reason this couldn't work for any two classes, after all.
public static T ConvertClass<T>(Object myObject)
{
T convertedObject;
try
{
convertedObject = (T)myObject;
return convertedObject;
}
catch
{
return default(T);
}
}
But that doesn't work. I get an exception thrown when it tries to
perform the cast, with the message:
Unable to cast object of type 'Validator' to type 'ValidTextBox'.
Which is clearly complete nonsense, as it will perform that cast if I
tell it to.
Anyone out there got an explanation?
Andy
ValidTextBox t = (ValidTextBox)v;
works just fine.
However, because v doesn't descend from t, I can't use "is" or "as". I
did want a safe way of casting though - so I tried the following code:
public static T ConvertClass<T>(Validator myValidator) where T :
Control
{
T convertedObject;
try
{
convertedObject = (T)myValidator;
return convertedObject;
}
catch
{
return default(T);
}
}
and that worked fine. So I thought I'd make it more generic - no
reason this couldn't work for any two classes, after all.
public static T ConvertClass<T>(Object myObject)
{
T convertedObject;
try
{
convertedObject = (T)myObject;
return convertedObject;
}
catch
{
return default(T);
}
}
But that doesn't work. I get an exception thrown when it tries to
perform the cast, with the message:
Unable to cast object of type 'Validator' to type 'ValidTextBox'.
Which is clearly complete nonsense, as it will perform that cast if I
tell it to.
Anyone out there got an explanation?
Andy