Grasshopper

algorithmic modeling for Rhino


hi all, can someone help me on this probably syntax error ?
thanks



String str = "hello";
if (str.GetType() = System.String )
{
Print("it's a string");
}

Views: 1228

Replies to This Discussion

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

myStr

"is" is a C# keyword. Alternatively, you can use GetType().

if(myObj.GetType() == typeof(string))

- Giulio

________________

giulio@mcneel.com
McNeel Europe, Barcelona

thank you !

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

sure it helps :) thx

RSS

About

Translate

Search

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service