What you have will work.
foreach (Item ThisItem in TheseItems)
{
//Display properties of Item instance “ThisItem” (Excluded for ease of reading)
if (ThisItem is Computer)
{
Computer computerItem = (Computer)ThisItem;
//Display distinct properties of Computer instance “ThisItem”
}
}
Or use the as
keyword for a slight optimization:
foreach (Item ThisItem in TheseItems)
{
//Display properties of Item instance “ThisItem” (Excluded for ease of reading)
var computerItem = ThisItem as Computer;
if (computerItem != null)
{
//Display distinct properties of Computer instance “ThisItem”
}
}
Also, a friend of mine wrote a nice utility class to helps with this. I thought I'd post it since it's turned out to be very useful.
foreach (Item ThisItem in TheseItems)
{
//Display properties of Item instance “ThisItem” (Excluded for ease of reading)
ThisItem.Match()
.Case<Computer>(comp => /* Do stuff with your computer */)
.Case<Television>(tv => /* Do stuff with your television */)
.Default(item => /* Do stuff with your item */);
}
The utility class looks something like this. Below gives the gist, and it's very expandable.
public class Matcher<TMatch>
{
private readonly TMatch _matchObj;
private bool _isMatched;
public Matcher(TMatch matchObj)
{
this._matchObj = matchObj;
}
public Matcher<TMatch> Case<TCase>(Action<TCase> action) where TCase : TMatch
{
if(this._matchObj is TCase)
{
this.DoCase(() => action((TCase)this._matchObj));
}
return this;
}
public void Default(Action<TMatch> action)
{
this.DoCase(() => action(this._matchObj));
}
private void DoCase(Action action)
{
if (!this._isMatched)
{
action();
this._isMatched = true;
}
}
}
public static class MatcherExtensions
{
public static Matcher<TMatch> Match<TMatch>(this TMatch matchObj)
{
return new Matcher<TMatch>(matchObj);
}
}