I am trying to verify whether a variable that is passed can be converted to a specific type. I have tried the following but can\'t get it to compile so I assume I\'m going
I think this is what you're looking for:
var myValue = "42";
int parsedValue;
if (Int32.TryParse(myValue, out parsedValue)) {
// it worked, and parsedValue is equal to 42
}
else {
// it did not work and parsedValue is unmodified
}
EDIT: Just to be clear, the operators is
and as
are used in the following ways...
The is
operator will return a boolean
value to indicate whether or not the object being tested either is the type specified or implements the interface specified. It's like asking the compiler "Is my variable this type?":
var someString = "test";
var result = someString is IComparable; // result will be true
The as
operator attempts to perform the conversion, and returns a null
reference if it can't. This is like telling the compiler "I would like to use this variable as this type":
var someString = "test";
var comparable = someString as IComparable; // comparable will be of type String
If you tried to do this:
var someString = "42";
// using Int32? because the type must be a reference type to be used with as operator
var someIntValue = someString as Int32?;
The compiler will issue an error:
Cannot convert type via a built-in converstion.
I know it's quite old but for someone looking for answer in modern way will leave post with response. From C#7 You can use new switch with pattern matching (https://docs.microsoft.com/pl-pl/dotnet/csharp/pattern-matching)
switch (myObject)
{
case PlayerObject playerObject:
//this is player object type and can use also playerObject because it's already casted
break;
case EnemyObject enemyObject:
//same here but we have enemy object type
break;
default:
break;
}
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?
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;
}
Try this
return myType.IsInstanceOfType(myObject);
Have you tried TryParse which has a boolean return value to indicate whether the conversion succeeded