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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Instance class members by name 1

Status
Not open for further replies.

bobisto

Programmer
Feb 13, 2002
111
MK
I've a class with private members and public property on them. I want to be able to instance class members by name. For example.
public class Position
{
private int _x;
private int _y;

public Position(){}

public int x
{
get {return _x;}
set {_x = value;}
}
public int y
{
get {return _y;}
set {_y = value;}
}

}

I want in code to be able to write also:
Position Position1 = new Position;
Position1("x") = 1;
Position1("y") = 2;

Please help!
 
It is not awfully clear what you are trying to achieve here, but the code you have put down will not compile. If you want to get it to do what I think you want it to do, then do this :

Code:
Position Position1 = new Position();
Position1.x = 1;
Position1.y = 2;
 
Maybe.
[System.Runtime.CompilerServices.CSharp.IndexerName("Item")]
public int this [char index] // Indexer declaration
{
get
{
char c = char.ToLower(index);
if (c == 'x')
return _X;
if (c == 'y')
return _y;
throw new System.IndexOutOfRangeException("x or y")
}
set
{
char c = char.ToLower(index);
if (c == 'x')
_x = value;
if (c == 'y')
_y = value;
throw new System.IndexOutOfRangeException("x or y")
}
}


Forms/Controls Resizing/Tabbing
Compare Code
Generate Sort Class in VB
Check To MS)
 
You can also use reflection to call methods, properties, etc.

Generally, you use GetType to return a variable of type Type, which then has methods to index into collections of that type's methods, properties, etc. You can then call them by name.

It's slow, but it works.

A better solution, if you're not sure what you'll be calling at runtime, would be to define an Interface or abstract base class. That way you'll be 100% of the method to call because the compiler enforces it.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Thanks to all for their posts.
For the helpfull one from JohnYingling, I've give a big red star.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top