I'd like to instantiate a variable but the exact class is not known at
compile time. In my specific application, I'm reading a message off
of an socket and interogating the first part of the message (with a
messageTypeId). Based on that messageTypeId I'd like to instantiate
the appropriate class.
I've started the method below but I'm wondering if there's a way to do
this without creating a huge switch statement. Any ideas??
TIA
public static AppMessage GetMessage(stri ng MessageString)
{
AppMessage rslt = null;
try
{
AppMessageType mt =
(AppMessageType )(Convert.ToInt 32(MessageStrin g.Substring(0, 3)));
switch (mt)
{
case AppMessageType. LoginRequest:
rslt = new MsgLoginRequest (MessageString) ;
break;
case AppMessageType. LoginResponse:
rslt = new MsgLoginRespons e(MessageString );
break;
case AppMessageType. AssignTable:
rslt = new MsgAssignTable( MessageString);
break;
default:
rslt = null;
break;
}
}
catch (Exception e)
{
//TODO:exception
}
return rslt;
}
compile time. In my specific application, I'm reading a message off
of an socket and interogating the first part of the message (with a
messageTypeId). Based on that messageTypeId I'd like to instantiate
the appropriate class.
I've started the method below but I'm wondering if there's a way to do
this without creating a huge switch statement. Any ideas??
TIA
public static AppMessage GetMessage(stri ng MessageString)
{
AppMessage rslt = null;
try
{
AppMessageType mt =
(AppMessageType )(Convert.ToInt 32(MessageStrin g.Substring(0, 3)));
switch (mt)
{
case AppMessageType. LoginRequest:
rslt = new MsgLoginRequest (MessageString) ;
break;
case AppMessageType. LoginResponse:
rslt = new MsgLoginRespons e(MessageString );
break;
case AppMessageType. AssignTable:
rslt = new MsgAssignTable( MessageString);
break;
default:
rslt = null;
break;
}
}
catch (Exception e)
{
//TODO:exception
}
return rslt;
}
Comment