Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic attributes in a class?

Status
Not open for further replies.

YvonneTsang

Programmer
Sep 28, 2001
37
CA
I was wondering if you are able to create a variant public variable in a class. I have a class that one of the variables can be set to one and only 1 of 4 different types/classes. Am I able to do this? Should I just have the other classes inherit from my main class? What is the easiest way to approach this problem? I am new to C# and it has been ages since I did Java so I am having trouble remembering what to do.

Essentially:

class MainOne
{
public string type;
public variant info;

public MainOne(string typedetails)
{
type = typedetails
if (type = "a")
{
info = new a()
}

etc
}


class a
class b
class c
class d


All of these classes will write to a seperate SQL table and I want to keep it easy to work with and only have 1 class write to each table. Thanks in advance for all of your help.
 
My question is are the four classes related to one another? (like do they inherit from the same base class, or from one another etc.)
And if you know that your variable can only have one type, why don't you do it like this:

class MainOne
{
public string type;
public a info;

public MainOne(string typedetails)
{
type = typedetails
if (type == "a")
{
info = new a()
}
else
{
info = null;
}


etc
}

I think though that it would be a better practice if all your classes a,b,c,d would be derived from a class or an interface named, by example, BaseClass. In this way you could do:

class MainOne
{
public string type;
public BaseClass info;

public MainOne(string typedetails)
{
type = typedetails
if (type == "a")
{
info = new a();
}
else
{
info = null;
}


etc
}

The difference is that if in the future you choose to provide support for the class b also, you can add a simple if in the constructor like this:

if (type == "a")
{
info = new a();
}
else if(type == "b")
{
info = new b();
}

Plus, you can easily add support for a new class e derived also from the BaseClass.
This is a kind of factory, if you ever heard of it.
Regards,
Alex
 
Alex -

I think using an Interface would be the way to go.
Although you could make a case for inheritance if the four classes were specialized in some way from their super class.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top