C#: Determine Type for (De-)Serialization
        Posted  
        
            by dbemerlin
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by dbemerlin
        
        
        
        Published on 2010-05-10T19:12:38Z
        Indexed on 
            2010/05/10
            19:24 UTC
        
        
        Read the original article
        Hit count: 228
        
Hi, i have a little problem implementing some serialization/deserialization logic.
I have several classes that each take a different type of Request object, all implementing a common interface and inheriting from a default implementation:
This is how i think it should be:
Requests
interface IRequest
{
  public String Action {get;set;}
}
class DefaultRequest : IRequest
{
  public String Action {get;set;}
}
class LoginRequest : DefaultRequest
{
  public String User {get;set;}
  public String Pass {get;set;} 
}
Handlers
interface IHandler<T>
{
  public Type GetRequestType();
  public IResponse HandleRequest(IModel model, T request);
}
class DefaultHandler<T> : IHandler<T> // Used as fallback if the handler cannot be determined
{
  public Type GetRequestType()
  {
     return /* ....... how to get the Type of T? ((new T()).GetType()) ? .......... */
  }
  public IResponse HandleRequest(IModel model, T request)
  {
      /* ... */
  }
}
class LoginHandler : DefaultHandler<LoginRequest>
{
  public IResponse HandleRequest(IModel mode, LoginRequest request)
  {
  }
}
Calling
class Controller
{
  public ProcessRequest(String action, String serializedRequest)
  {
    IHandler handler = GetHandlerForAction(action);
    IRequest request = serializer.Deserialize<handler.GetRequestType()>(serializedRequest);
    handler(this.Model, request);
  }
}
Is what i think of even possible?
My current Solution is that each handler gets the serialized String and is itself responsible for deserialization. This is not a good solution as it contains duplicate code, the beginning of each HandleRequest method looks the same (FooRequest request = Deserialize(serializedRequest); + try/catch and other Error Handling on failed deserialization).
Embedding type information into the serialized Data is not possible and not intended.
Thanks for any Hints.
© Stack Overflow or respective owner