- Home /
if (!(apple is Vege)) then...
this is a syntax question. is there a neater way to write:
public Fruit apple; // Fruit and Vege are my classes
if (!(apple is Vege)) // do something
something like:
if (apple !is Vege) // do something
would be ideal.
sorry i wasn't clear... apple is a variable of type Fruit, and both Fruit and Vege are classes. so (apple is Vege) is a check of whether apple is of type Vege.
Answer by whydoidoit · May 07, 2013 at 08:03 AM
Actually it is always faster to write:
var vege = apple as Vege;
if(vege != null) ...
Presuming you are going to use the Vege class. But it's not any neater :)
You have the neatest syntax as ugly as it may be.
You could write an extension method, probably slower:
public static class TypeHelper
{
public static bool Isnt<T>(this object test)
{
return !typeof(T).IsAssignableFrom(test.GetType());
}
}
if(someObject.Isnt<Vege>())
thanks buddy. you're right that the assignment method works well if one is going to use it afterwards. though since i'm just checking the type, all the syntaxes so far look just about as good as each other.
the extension method works (except for needing to complicate things with an extension), though i am surprise to find that c# doesn't already have that built-in somewhere. anyway, thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613101735im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to store class type in variable 2 Answers
Public class used in another class (C#) 1 Answer
Get Superclass of Subclass in Unityscript 2 Answers
calling a class named by a string -1 Answers
Class hierarchy, gameObject, Raycast 1 Answer