is Keyword Question

  • Thread starter Thread starter jm
  • Start date Start date
J

jm

From MSDN:

http://windowssdk.msdn.microsoft.com/en-us/library/scekt9xw.aspx

C# Language Reference
is (C# Reference)

Checks if an object is compatible with a given type. For example, it
can be determined if an object is compatible with the string type like
this:

if (obj is string)
{
}

I would understand this if it had said (obj is class1), but what would
it mean to say that obj is string? Is string special? Could it have
said (obj is int)? I thought "is" in C# was just for reference types.

Thank you.
 
jm said:
I would understand this if it had said (obj is class1), but what would
it mean to say that obj is string? Is string special? Could it have
said (obj is int)? I thought "is" in C# was just for reference types.

"string" *is* a reference type.
 
I thought "is" in C# was just for reference types.

In addition to what Peter wrote, the is operator can be used on value
types as well. Useful for checking the type of boxed values, i.e.

object o = 5;
Consle.WriteLine(o is int);


Mattias
 
Mattias said:
In addition to what Peter wrote, the is operator can be used on value
types as well. Useful for checking the type of boxed values, i.e.

object o = 5;
Consle.WriteLine(o is int);
But what does it mean for an reference type to be an int? That's
what's throwing me.
 
jm said:
But what does it mean for an reference type to be an int? That's
what's throwing me.

Value types can be "boxed" - placed on the managed heap. When a value type
is boxed, a copy of the value is placed on the managed heap and can be
accessed as a System.Object, just like any managed type.

examples:

int i = 5;
object o = i; // o references a "boxed" copy of i

if (o is int)
{
Console.WriteLine("It's an int!");
}

o = 6; // o now references a different boxed int
// but the value of i is unchanged

if (i == 5)
{
Console.WriteLine("i didn't change");
}

o.ToString(); // returns "6"

HTH

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top