Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a UserControl as a specific type of user control

Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties.

foreach(UserControl uc in plhMediaBuys.Controls)
{
    uc.PulblicPropertyIWantAccessTo;
}
like image 436
angelo Avatar asked Oct 22 '08 18:10

angelo


3 Answers

foreach(UserControl uc in plhMediaBuys.Controls) {
    MyControl c = uc as MyControl;
    if (c != null) {
        c.PublicPropertyIWantAccessTo;
    }
}
like image 115
Chris Pietschmann Avatar answered Oct 07 '22 16:10

Chris Pietschmann


foreach(UserControl uc in plhMediaBuys.Controls)
{
  if (uc is MySpecificType)
  {
    return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
  }
}
like image 32
Kon Avatar answered Oct 07 '22 16:10

Kon


Casting

I prefer to use:

foreach(UserControl uc in plhMediaBuys.Controls)
{
    ParticularUCType myControl = uc as ParticularUCType;
    if (myControl != null)
    {
        // do stuff with myControl.PulblicPropertyIWantAccessTo;
    }
}

Mainly because using the is keyword causes two (quasi-expensive) casts:

if( uc is ParticularUCType ) // one cast to test if it is the type
{
    ParticularUCType myControl = (ParticularUCType)uc; // second cast
    ParticularUCType myControl = uc as ParticularUCType; // same deal this way
    // do stuff with myControl.PulblicPropertyIWantAccessTo;
}

References

  • The 3 Cast Operators in C#
  • Type Casting Impact over Execution Performance in C#
like image 3
wprl Avatar answered Oct 07 '22 15:10

wprl