angelo
angelo

Reputation: 482

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;
}

Upvotes: 7

Views: 16121

Answers (3)

wprl
wprl

Reputation: 25397

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

Upvotes: 3

Chris Pietschmann
Chris Pietschmann

Reputation: 29885

foreach(UserControl uc in plhMediaBuys.Controls) {
    MyControl c = uc as MyControl;
    if (c != null) {
        c.PublicPropertyIWantAccessTo;
    }
}

Upvotes: 9

Kon
Kon

Reputation: 27441

foreach(UserControl uc in plhMediaBuys.Controls)
{
  if (uc is MySpecificType)
  {
    return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
  }
}

Upvotes: 5

Related Questions