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");
}
Comments
- Anonymous
March 25, 2004
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...
} - Anonymous
March 25, 2004
The comment has been removed - Anonymous
March 26, 2004
The comment has been removed