best way to evaluate what type of control there is

whats faster

this:

if(c.GetType().ToString() == "Sytem.Web.Ui.WebControls.Label")
{
//something
}

or this:

if(c.GetType() == typeof(Sytem.Web.Ui.WebControls.Label))
{
//something
}

just curious,

thanks

mcm




Answer this question

best way to evaluate what type of control there is

  • RickRSL

    As Chris Vega says, you can use the is keyword to checks if an object is compatible with a given type.
    An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.


    Control control = new Label();

    if( control is Label )
    {
    // TODO: Add logic.
    }



    You can also use the as keyword to perform conversions between compatible reference types.
    The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.

    Control control = new Label();

    Label label = control as Label;

    if( label != null )
    {
    // TODO: Use the label.
    }
    else
    {
    // control could not be casted to a Label.
    }



    Take a look at the Cast expressions page for more information about casting.


  • lauramc

    Don't compare types using its string representation. Instead, you can compare types using either of these two methods:



    if (c is System.Web.UI.WebControls.Label)
    {
    // TODO: True code here...
    }



    Or (specific type comparison):



    if (c.GetType() == typeof(System.Web.UI.WebControls.Label))
    {
    // TODO: True code here...
    }



    Regards,

    -chris

  • best way to evaluate what type of control there is