algorithmic modeling for Rhino
Hi Raf,
sure. You use this pattern when you do not know the type, for example:
object myObj = "Hello";
if(myObj is string)
{
Print("It's a string.");
//We know it's a string, so we migth want to cast to it
string myStr = (string)myObj;
//Now we can print it
Print(myStr);
}
- Giulio
________________
giulio@mcneel.com
McNeel Europe, Barcelona
"is" is a C# keyword. Alternatively, you can use GetType().
if(myObj.GetType() == typeof(string))
- Giulio
________________
giulio@mcneel.com
McNeel Europe, Barcelona
Another alternative in C# would be the "as" keyword which will attempt to cast if the type is a match
string mystr = myObj as string;
if( mystr!=null )
{
Print("It's a string!");
Print(mystr);
}
Now (thanks Steve) we showed three ways, so let's have a look at some differences. My preference is to:
1) use is if I do not need to cast afterwards, as this method is readable. Like as and casts, it also checks for compatible types (for example LineCurve that inherits from Curve):
if (myObj is Curve)
{
Print("It's a curve (and not null).");
2) use as if I'd otherwise need to have the object cast afterwards. This is faster as it avoids the double cast (once for is, then the real ()cast), but might add more variables in the method and cannot be used with value types (structs):
string mystr = myObj as string;
if (mystr != null)
{
3) use GetType() == typeof() if you want to check for the precise type (or maybe with structs, as they cannot have inherited types). There are also some rare cases with generic constrains that benefit from this. Eventually, check against null beforehand, as GetType() is an instance method:
if(myObj.GetType() == typeof(T))
{
I hope this helps,
- Giulio
____________
giulio@mcneel.com
McNeel Europe, Barcelona
Welcome to
Grasshopper
Added by Parametric House 0 Comments 0 Likes
Added by Parametric House 0 Comments 0 Likes
Added by Parametric House 0 Comments 0 Likes
Added by Parametric House 0 Comments 0 Likes
Added by Parametric House 0 Comments 0 Likes
© 2024 Created by Scott Davidson. Powered by