title: Declare variable of different type using If Else-If statement
body: <p>I have a method which receives events based on which item is clicked within a TreeView.</p>
  
  <p>I can add items to both a TreeView and a TreeViewItem in exactly the same way so have attempted to assign <code>item</code> as either TreeView or TreeViewItem based on the <code>state.sender</code> type. However, currently the only way I can make it work is to assign item as an object first.</p>
  
  <pre><code>private void ProcessEvent(Events.GetEventsResp resp, CustomAsyncStateContainer state)
  {
      object item = new object();   //must be a better way than this?
      if (state.sender is TreeViewItem)
          item = (TreeViewItem)state.sender;
  
      else if (state.sender is TreeView)
          item = (TreeView)state.sender;
  
       //other code
  }
  </code></pre>
  
  <p>I assume this is called unboxing? Is there a better way to do what I'm attempting?</p>
  
  <p>Edit: Below is the remaining code. I hadn't finished writing it when asking the question and have now realised that <code>object item = new object();</code> is not going to work in this case.</p>
  
  <pre><code>private void DisplayGetEvent(Events.GetEventsResp resp, CustomAsyncStateContainer state)
  {
      object node = new object();
      if (state.sender is TreeViewItem)
          node = (TreeViewItem)state.sender;
  
      else if (state.sender is TreeView)
          node = (TreeView)state.sender;
  
      if (resp.eventItems != null)
      {
          Events.UXEvent[] eventItems = resp.eventItems;
          Array.Sort(eventItems, new UXWrapper.UXEventComparer());
  
          int itemCount = eventItems.Length;
          TreeViewItem tvItem = new TreeViewItem;
          for (int i = 0; i &lt; itemCount; i++)
          {
  
              tvItem.Header = eventItems[i].name;
              tvItem.Tag = eventItems[i];
  
              node.Items.Add(tvItem);
  
          }
  
      }
  }
  </code></pre>