473,395 Members | 1,530 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Dynamic class creation

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(string MessageString)
{
AppMessage rslt = null;
try
{
AppMessageType mt =
(AppMessageType)(Convert.ToInt32(MessageString.Sub string(0, 3)));

switch (mt)
{
case AppMessageType.LoginRequest:
rslt = new MsgLoginRequest(MessageString);
break;
case AppMessageType.LoginResponse:
rslt = new MsgLoginResponse(MessageString);
break;
case AppMessageType.AssignTable:
rslt = new MsgAssignTable(MessageString);
break;
default:
rslt = null;
break;
}
}
catch (Exception e)
{
//TODO:exception
}
return rslt;
}
Nov 16 '05 #1
2 5105
Mark,

If all of the types have parameterless constructors, then I would do the
following. First, I would create a static Hashtable (or a Dictionary<K, V>
in .NET 2.0, where K is AppMessageType and V is Type). Once you have that,
I would create a static constructor which would populate this hash table,
with the key being the values from the AppMessageType enumeration, and the
values being the Type that represents the type of object they map to. If
you wanted to get really fancy, you could create an attribute that you
attach to each value in the enumeration, and get reflection to get them (in
which case, you don't need the hash table).

Once you have that, you just have to do a lookup for the type, and then
call the static CreateInstance method on the Activator class, passing in the
Type that is returned from the lookup.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mark Sisson" <ma**@corporatedigital.com> wrote in message
news:88**************************@posting.google.c om...
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(string MessageString)
{
AppMessage rslt = null;
try
{
AppMessageType mt =
(AppMessageType)(Convert.ToInt32(MessageString.Sub string(0, 3)));

switch (mt)
{
case AppMessageType.LoginRequest:
rslt = new MsgLoginRequest(MessageString);
break;
case AppMessageType.LoginResponse:
rslt = new MsgLoginResponse(MessageString);
break;
case AppMessageType.AssignTable:
rslt = new MsgAssignTable(MessageString);
break;
default:
rslt = null;
break;
}
}
catch (Exception e)
{
//TODO:exception
}
return rslt;
}

Nov 16 '05 #2
Before I type this, I am not recommending this approach as being better
than a switch -- depending on the number of cases you expect, a switch
may be the appropriate answer. If you have a large number of checks,
some combination of a chain of control or prototype factory might be
easier to maintain.

For example, if you have a factor class that returns an AppMessage
object on a call to the static Process method. When it is called, it
maintains an internal collection of instances of your objects derived
from AppMessage (MsgLoginRequest,MsgLoginResponse ..etc..) and walks
through each object in the collection asking it if it knows how to
handle the AppMessageType that you pass in. If the object does know how
to handle the message it could either return a reference to the instance
from the factory -- or it could clone the instance in the factory and
return a unique instance (depending on your requirements.)

This approach encapsulates the logic of which class can handle which
message directly into the class that handles that message.

John

Mark Sisson wrote:
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(string MessageString)
{
AppMessage rslt = null;
try
{
AppMessageType mt =
(AppMessageType)(Convert.ToInt32(MessageString.Sub string(0, 3)));

switch (mt)
{
case AppMessageType.LoginRequest:
rslt = new MsgLoginRequest(MessageString);
break;
case AppMessageType.LoginResponse:
rslt = new MsgLoginResponse(MessageString);
break;
case AppMessageType.AssignTable:
rslt = new MsgAssignTable(MessageString);
break;
default:
rslt = null;
break;
}
}
catch (Exception e)
{
//TODO:exception
}
return rslt;
}

Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Eddie de Bear | last post by:
Hi, A project I am working on has a requirement for dynamic menus. For the most part this works really well. The menus I'm creating a based on files and directories, so naturally the menu...
4
by: Leslaw Bieniasz | last post by:
Cracow, 20.10.2004 Hello, As far as I understand, the generic programming basically consists in using templates for achieving a static polymorphism of the various code fragments, and their...
1
by: andrew queisser | last post by:
I've been trying to dynamically create a class DevT that's derived from a generic base GenBase<T>. It doesn't seem to work. I'm attaching a code sample below that illustrates the problem. ...
15
by: rwf_20 | last post by:
I just wanted to throw this up here in case anyone smarter than me has a suggestion/workaround: Problem: I have a classic producer/consumer system which accepts 'commands' from a socket and...
0
by: Pascal Costanza | last post by:
Dynamic Languages Day @ Vrije Universiteit Brussel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monday, February 13, 2006, VUB Campus Etterbeek The VUB (Programming Technology Lab,...
1
by: None | last post by:
Dynamic array creation Hi all... here's a good one for you... I have a situation where I have some bean, and I need to populate an array field in it... here's the problem... I do not know the...
1
by: dav3 | last post by:
Any help here is appreciated folks. First in my Person class the comments = errors visual basics is giving me and I am not sure why. Also when i try and set up my array of pointers to Student...
16
by: manatlan | last post by:
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance "b". I know it's possible by hacking "b" with setattr() methods. But i'd like to do...
3
by: arunank | last post by:
Hi, The following code for dynamic table creation is not working. Can anyone please help me. The dynamically created rows and columns are not getting populated. CODE: ========= <html>
1
by: cdmsenthil | last post by:
I have an Infragistics UltrawebGrid . Each Row in the grid is attached to a context menu using Infragistics CSOM Upon click on the menu, I am creating an Iframe dynamically which points to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.