Referencing each property in a object using a loop...

Apexprim8

Member
Joined
Oct 6, 2005
Messages
18
Location
Cheshire, United Kingdom
Programming Experience
Beginner
Hi.
I have an object which has several public properties named rm1, rm2, rm3 ... rm18. I want to be able to write a loop (for i = 1 to 18) in another class, that allows me to reference the rm(i) numbered property. How do I write this in code? I have already created myObject in the other class that I want to execute the loop from.

Regards,
ape:cool:
 
Hey ape,

Sounds like you'd be better off using an array in the first class. ie

VB.NET:
private rm(18) as String '(Or whatever datatype)

Public property MyRm as String()

I'm not aware of anyway of dynamically referencing properties.
 
You can dynamically reference properties through the Type class, but BadgerByte's suggestion is better. You should use either an array or a collection, depending on whether you want the number of items to change or not, and you should make the property ReadOnly. This means that, from the outside, you can set the items within the array or collection but you cannot assign a new array or collection object to the property itself. Also, what's with those dodgy names? "rm1" may be OK for a local variable but a public property should be named much more descriptively. It's up to you, obviously, but that's the widely accepted convention.
 
BadgerByte said:
Hey ape,

Sounds like you'd be better off using an array in the first class. ie

VB.NET:
private rm(18) as String '(Or whatever datatype)
 
Public property MyRm as String()

I'm not aware of anyway of dynamically referencing properties.

It is "possible", but chances are if you are looking at this then you need a better data structure. The array suggestion is good.

One way to dynamically reference a property of an object:

System.Web.UI.DataBinder.Eval(yourobject, "rm1")

You could use a loop to construct the property name.
 
Back
Top