Can I check if a variable can be cast to a specified type?
Solution 1:
Use the "as" operator to attempt a cast:
var myObject = something as String;
if (myObject != null)
{
// successfully cast
}
else
{
// cast failed
}
If the cast fails, no exception is thrown, but the destination object will be Null.
EDIT:
if you know what type of result you want, you can use a helper method like this:
public static Object TryConvertTo<T>(string input)
{
Object result = null;
try
{
result = Convert.ChangeType(input, typeof(T));
}
catch
{
}
return result;
}
Solution 2:
Checkout this link: http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx
The is operator is used to check whether the run-time type of an object is compatible with a given type. The is operator is used in an expression of the form:
if (expression is type){
// do magic trick
}
Something you can use?