I’m currently receiving a serialized object through a socket connection, this works flawlessly. I’m deserializing it fine also. Now, I want the client to send more than one object type (or class) through the network.
This is how i deserialize my object onto it’s Type ‘MyClass’:
var m = new MemoryStream(Convert.FromBase64String(dataReceived));
var b = new BinaryFormatter();
var o = (MyClass)b.Deserialize(m);
Now, if I’d like to receive more than 1 object type I could either make a method that can cast it to any type supported or send a header which will tell me the type the object is and then cast it. I prefer the FIRST way.
The thing is, I can’t cast it with GetType() of course, and using the name property would result in something with a switch of strings which I dislike. So I decided I could do either:
object objectReceived = b.Deserialize(m);
if(o is MyClass){
MyClass myClass = (MyClass) objectReceived;
}
else if (o is AnotherClass){
AnotherClass myOtherClass = (AnotherClass) objectReceived;
}
(I could also do something with the as operator, but that will make me check for nulls afterwards. For example)
var MyClass = objectReceived as MyClass;
var AnotherClass = objectReceived as AnotherClass
OR I could implement an interface that every object sent through the network will implement, cast the object as that interface, which will return it’s type, and then cast it accordingly!
The thing is, I already have that working code, but I can’t figure out a clean way to code that interface. What should the interface’s method return? A type? A string? I don’t know really. This is why I tell myself: well, as I have working code, if it’s good practice and easy to maintain, I won’t get myself into the trouble of making an interface which I don’t know how to now because of time constraints.
So that’s my question: Is my approach correct/good practice? Or is the interface approach better?
Thanks a lot for your help guys!!
Why not use Generics?
You can create a common deserialization method like so:
Any then call it like:
Generics
With generics when you call
MyDeserialize<MyClass>(dataReceived);you make the method think thatTisMyClass.Imagine it doing this:
Obviously you can pass any Type (class if you prefer) you like in between the
<>‘s and it will use that type instead.