Welcome to MSDN Blogs Sign in | Join | Help

is keyword

I don't know how I missed the is keyword in C#. I must have been asleep or something when I read about this. Up till now I've been getting the type of an object and comparing to the typeof() a class.

object foo = "bar";

if (foo is string)
{
    Console.WriteLine("foo is a string");
}

if (foo.GetType() == typeof(string))
{
    Console.WriteLine("foo is a string");
}
Published Friday, March 26, 2004 8:47 AM by omars
Filed under:

Comments

# re: is keyword

Friday, March 26, 2004 1:23 AM by Scott Galloway
I tend to use the 'as' keyword with a test for null. Reason is that when I'm checking a type, I usually want to go on and cast to that type - your example above is of course more suited for is...but say, sor example I want to cast to a string.

string testString = testObject as string;
if(testString != null)
{
//Do whatever I want with the string...
}

# re: is keyword

Friday, March 26, 2004 1:42 AM by Ivan Towlson
Note that "is" and "GetType() ==" do different things in the presence of derivation hierarchies.

Thus:

class Derived : Base { ... }
object foo = new Derived();

(foo is Base) will return true
(foo.GetType() == typeof(Base)) will return false

Usually the "is" behaviour is what you want, which is another reason to avoid the GetType() approach.

# re: is keyword

Friday, March 26, 2004 11:26 AM by Omar Shahine
Ivan, that is a great point and something I just used the other day. I was trying to do a comparison using (foo.GetType() == typeof(Base)) and it kept failing .
New Comments to this post are disabled
 
Page view tracker