type comparisons

Published 02-09-2006 4:40 PM | jokiz

i just browsed on the windows forms designer section of msdn forums and i see a post of this guy helping another about designers of course. what hit me was the way he tests if an object instance is of certain type

foreach(Control control in this.Controls)

{

    if(control.GetType() == "System.Windows.Forms.TextBox")

    {

        //do whatever...

    }

}


i hate string comparisons for determining types and you should refrain from doing the above code and use this:


foreach(Control control in this.Controls)

{

    TextBox textBox = control as TextBox;

    if(textBox != null)

    {

        //do whatever...

    }

}

Filed under: ,

Comments

# keithrull said on February 9, 2006 5:23 PM:

i used to be a victim of this style before :P things change when you start realizing the true ways and means on how to validate objects using the .NET way. :)

# keithrull said on February 9, 2006 5:32 PM:

btw, he probaly is from the vb.net realm.. in vb.net 1.1 we dont have the as operator... in 2.0 we have something in similar called trycast()

# jokiz said on February 9, 2006 6:09 PM:

from a vb.net perspective, i know they can use equality of types, i dunno the syntax but i've come across it before...

# jokiz said on February 9, 2006 6:20 PM:

they have is pre, if typeof control is TextBox

# keithrull said on February 9, 2006 9:17 PM:

i think the typeof thingy is different from the as statement. try mo tol sa reflector.. trycast lalabas :)

# jokiz said on February 10, 2006 1:02 AM:

both is and as operators tries a cast internally kaya nga mas efficient and as kasi you have already cached the object to a variable when you want to do something with the validated type instance. is statements are perf hit for fxcop if you try to cast the instance after an is statement

# Alex said on November 13, 2006 2:59 AM:

I don't understand why we aren't able to just do the following:

if(typeof(myObj) == System.SomeType){

}

But this gives a syntax error!!?

Madness.