typeof()

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need to do the following but it doesn't compile

if(typeof(listBox1.Items[index]) == typeof(string)){
return;
}


typeof(listBox1.Items[index]) doesn't work at all. My listBox has 2 types of items in them and I need to know what kind of item a user clicked on so I can use it for drag and drop
 
Eric said:
I need to do the following but it doesn't compile

if(typeof(listBox1.Items[index]) == typeof(string)){
return;
}

No indeed, because the typeof(<x>) operator expects <x> to be a type
name. I believe you want GetType() in order to make it compile:

if (listBox1.Items[index].GetType() == typeof(string))

However, a better solution is to use the "is" operator:

if (listBox1.Items[index] is string)
{
....
}

Or possibly the "as" operator if you're going to use the value:

string value = listBox1.Items[index] as string;
if (value != null)
{
....
}
 
Eric, you probably want to use the "is", or "as" keywords instead:

if( listBox1.Items[index] is string) {...

or

string selectedVal = listBox1.Items[index] as string;
if( null != selectedVal ) { ...

The reason that typeof(listBox1.Items[index]) doesn't compile is because the
typeof() operator takes a type, not an object
(so typeof(string) or typeof(myclass) work, but not typeof(
instanceOfMyClass))

If you wantd to check types this way, you can use the .GetType() method that
exists on any object:
if( listBox1.Items[index].GetType() == typeof(string) ) {...

but the is method above is definitely easier to read.

-Philip


Eric said:
I need to do the following but it doesn't compile

if(typeof(listBox1.Items[index]) == typeof(string)){
return;
}


typeof(listBox1.Items[index]) doesn't work at all. My listBox has 2
types of items in them and I need to know what kind of item a user clicked
on so I can use it for drag and drop
 
Philip Rieck said:
if( null != selectedVal )

Any reason for using that syntax for comparison? I personally find it
less easy to read than

if (selectedVal != null)

and you don't have the problem in C where if you accidentally did

if (selectedVal = null)

you'd end up with an assignment.
 
Jon -- Bad habit from C++ days. I try not to do it anymore, but my fingers
remember it that way and I forget to stop them.

Readability for me is about equal, but I always get tagged at code review
time. Sorry to inflict it on you guys here!


-Philip
 
Back
Top