Coding Problem, Help Needed

B

batista

Hello to ALL,

I'll explain my problem by pseudo code

class A
{
int x;
char y;
string z;
}

class B
{
GetVariable(int i)
{
A a = new A();
//Now I want to return the ith varaible
//of class A
}
}

class C
{
GetVar()
{
B b = new B();
b.GetVariable(0) //it shud return x
b.GetVariable(1) //it shud return y
b.GetVariable(2) //it shud return z
}
}

Now how do I implement the GetVariable(int i), in C#
The reason I have class B is because there are lot's of classes
like class A, and i don't want to edit them all.

Any Suggestions...

Thanks In advance...
Cheers...

Bye
 
N

Nicholas Paldino [.NET/C# MVP]

batista,

You will have to make sure that the original class declares GetVariable
as virtual, so that it can be overridden by derived classes. If it is not,
then there is little you could do (you could shadow it with the new keyword,
but that is evil).

Hope this helps.
 
B

batista

Thanks For Replies,

Pipo and Nicholas Paldino,

Nicholas Paldino, I understand that I'll need to declare GetVariable()
virtual in all classes,
but how do i implement a function like this.

I mean how do i number the variables of a class, so that i can ask for
ith variable in the class.

Plz help me on that...
Thanks In Advance...
Cheers...

Bye
 
G

Guest

batista said:
I mean how do i number the variables of a class, so that i can ask for
ith variable in the class.

AFAIK you'll have to hardcode it. The compiler is free to reorder
variables inside a data structure to optimize performance. ie putting 4
chars sequentially so they all fell in the same 32bit chunk when on the
memory bus.
 
D

Deviant

You could use Reflection to enumerate the fields in the class (although
they would have to be public, which seems to defeat the object).

The easiest solution would be to replace all the variables in Class A
with an object array..
 
J

justncase80

this is ugly but in desperation you could just do somethign like this:

object GetVariable(int x)
{
switch(x)
{
case(0):
return x;
case(1):
return y;
case(2):
return z;
default: return null;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top