user007
user007

Reputation: 1084

How to cast with different types

Here is my code:

public class MyButton
{
  Object button;

  public MyButton(System.Windows.Forms.ToolStripButton button)
  {
    this.button = button;
  }

  public MyButton(System.Windows.Forms.ToolStripSplitButton button)
  {
    this.button = button;
  }

  public void EnableButton(bool enable)
  {
    if (button is System.Windows.Forms.ToolStripButton)
      ((System.Windows.Forms.ToolStripButton)button).Enabled = enable;
    else if (button is System.Windows.Forms.ToolStripSplitButton)
      ((System.Windows.Forms.ToolStripSplitButton)button).Enabled = enable;
  }

  //...
}

I was wondering can I make this code shorter? Can I cast it by its type somehow? Something like this:

public void EnableButton(bool enable)
{
  ((FakeFuctionToGetCastType(button))button).Enabled = enable;
}

Of course its my fake function... So is there a way to do so?

Upvotes: 2

Views: 263

Answers (4)

Joel Etherton
Joel Etherton

Reputation: 37533

I would make it generic:

public class MyButton<T> where T : System.Windows.Forms.ToolStripItem
{
    T button;

    public MyButton(T button) 
    {
        this.button = button;
    }

    public void EnableButton(bool enable)
    {
        this.button.Enabled = enable;
    }
}

Edit: As a side note, you'll want the constraint to be as tight as possible in the assignment of the generic. If you can find a common inherited class for the controls you want to use that is closer than Control then you should use that one.

Upvotes: 1

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

Because you are using the is operator so I assume that ToolStripButton and ToolStripSplitButton extend Button .Thus Enabled is a property defined in the base class Button.So, Enabled will be called polymorphically , if the actual type is ToolStripButton, then its Enabled will be called. So this should be enough

  Button button;
  button.Enabled=enable;

or

 this.Enabled=enable;

Upvotes: 1

ilivewithian
ilivewithian

Reputation: 19692

You can just do this;

public class Button
{
   System.Windows.Forms.ToolStripItem button;

  public MyButton(System.Windows.Forms.ToolStripItem button)
  {
    this.button = button;
  }

  public void EnableButton(bool enable)
  {
    button.Enable = enable;
  }

  //...
}

Upvotes: 0

Josh C.
Josh C.

Reputation: 4363

If the Enabled property is on the base class Button (it probably is), you don't need to cast. Just do this:

public class Button
{
  Control button;

  public Button(Control button)
  {
    this.button = button;
  }

  public void EnableButton(bool enable)
  {
    button.Enabled = enable;
  }

  //...
}

If the Enabled property is not on the Button base class you can do this:

((dynamic)Button).Enabled = enable;

Upvotes: 0

Related Questions