Hi,
Can anyone please suggest how I can get type of a Stream i.e. whether its a memorystream or a filestream?
AK
Printable View
Hi,
Can anyone please suggest how I can get type of a Stream i.e. whether its a memorystream or a filestream?
AK
This is a way to do it:
Code:try{
object of mem stream = explicit cast to memstream <- object o
catch( InvalidCastException) {
try {
object of filestream = explicit cast to filestream <-object o
} catch ( InvalidCastException) {
//do some more error handling
}
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: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
}
else
{
FileStream fileStream = obj as FileStream;
if (fileStream != null)
{
//obj is a FileStream
}
else
{
//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 ReflectionCode: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
}
The second way is also pretty simple.Is this better than the first way? Well, it's pretty easy to read, but I'm not sure how expensive reflection is.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
}
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.
Yeah pianorain you are right, personally I dont use the solution I posted earlier myself.
I myself use typeof ( since its the most readable way ) ... but I wanted to see how Angkar would respond ( why ? check my post at the "C# connect to site" thread. ) .
( guess maybe im overreacting... if so it's probably because im having exams right now :) )