Eww...that's a pretty rough way to do it, GanglyLamb. There's a couple of ways to do this in C#.
Using as
The first way uses the as keyword:
Code:
void DoWork(object obj)
{
MemoryStream memStream = obj as MemoryStream;
if (memStream != null)
{
//obj is a MemoryStream
}
else
{
FileStream fileStream = obj as FileStream;
if (fileStream != null)
{
//obj is a FileStream
}
else
{
//obj is not a FileStream or a MemoryStream
}
}
}
Coding in this pattern has some ugly implications; the nesting quickly becomes out of control if you're doing this. Each extra type you're checking becomes another level of nesting. You can remove some of the nesting by putting a return at the end of each if block.
Code:
void DoWork(object obj)
{
MemoryStream memStream = obj as MemoryStream;
if (memStream != null)
{
//obj is a MemoryStream
return;
}
FileStream fileStream = obj as FileStream;
if (fileStream != null)
{
//obj is a FileStream
return;
}
//obj is not a FileStream or a MemoryStream
}
Personally, I like to limit the scope of my local variables, so I'd use:
Code:
void DoWork(object obj)
{
{
MemoryStream memStream = obj as MemoryStream;
if (memStream != null)
{
//obj is a MemoryStream
return;
}
}
{
FileStream fileStream = obj as FileStream;
if (fileStream != null)
{
//obj is a FileStream
return;
}
}
//obj is not a FileStream or a MemoryStream
}
Using Reflection
The second way is also pretty simple.
Code:
void DoWork(object obj)
{
if (obj.GetType() == typeof(MemoryStream))
{
MemoryStream memStream = (MemoryStream)obj;
//obj is a MemoryStream
return;
}
if (obj.GetType() == typeof(MemoryStream))
{
FileStream fileStream = (FileStream)obj;
//obj is a FileStream
return;
}
//obj is not a FileStream or a MemoryStream
}
Is this better than the first way? Well, it's pretty easy to read, but I'm not sure how expensive reflection is.
Why are you doing this at all?
In general, though, when you need a kind of switch statement for types, a red flag pops up in my mind. Consider using some sort of polymorphic behavior instead of this kind of solution.