The is keyword

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

I just want to check with you the usage of the is keyword is only relevant
when having reference type.

Is that correct?

//Tony
 
I just want to check with you the usage of the is keyword is only relevant
when having reference type.

Is that correct?

Well, the expression on the left has to be a reference type, but the
type name on the right could be a value type when it comes to boxing:

object o = 10;
if (o is int)
{
// Yup
}

Jon
 
Hello!

I just want to check with you the usage of the is keyword is only relevant
when having reference type.

Is that correct?

//Tony

the left side at least, you can do object1 is Int32.

You will fnid a different situation with the "as" operator, there the
second operator should be a reference type.
so this expression is valid:

int i = 23;
object e = i as object;
 
Well, the expression on the left has to be a reference type

It doesn't have to be... of course the compiler knows that structs can't
be subclassed, so will raise warnings about unnecessary usage, but
consider generics:

static int? CompareToDefault<T>(T value) where T : struct
{
if (value is IComparable<T>)
{
return Comparer<T>.Default.Compare(default(T), value);
}
else
{
return null;
}
}

The left hand operand is definitely a value-type...

Marc
 
It doesn't have to be... of course the compiler knows that structs can't
be subclassed, so will raise warnings about unnecessary usage, but
consider generics:

Ooh, very true. Interesting example :)

Can you think of any non-generic value type examples? I suspect
*those* are impossible, because other than generic cases, if the
compiler knows it's a value type, it knows the exact type. I could be
missing something though.

Jon
 
Well, you can still *use* is with known value-types; but the compiler
will ignore you ;-p But it is a warning, not an error...

But no, I can't think of any useful, non-generic value-type examples of
"is".

Marc
 
It happens that Ignacio Machin ( .NET/ C# MVP ) formulated :
the left side at least, you can do object1 is Int32.

You will fnid a different situation with the "as" operator, there the
second operator should be a reference type.
so this expression is valid:

int i = 23;
object e = i as object;

Not quite, a nullable type will work as well. The main point is that
"null" should be an acceptable value for the receiving type.

object o = "nop";
int? i = o as int?; // i becomes null

or you could use
int i2 = o as int? ?? 2; // i2 becomes 2

Hans Kesting
 
Back
Top