views:

422

answers:

4

I suspect this question illustrates my lack of understanding about what's going on behind the scenes in C#, but hey...

While doing a CRM SDK project in C# that involved a number of private variables (which were CRM objects called "lists", but that doesn't really matter), I found I was repeating nearly the same lines of code. I tried shoving the private variables into an array of type "list", and then looping over this array, and setting the variables one by one. Except that, of course, that didn't work, because (I think) what I'm actually working with is a copy of my list of variables.

Anyway, to cut a long story short, is there a way to set a load of private variables in a loop? Am I missing something very obvious, or is what I want to do not actually possible?

A: 

Normally you would create a Reset() method that ... resets the members of the object.

280Z28
A: 

If you are using an object/class then the values in the array should be referenced, as opposed to using copies of the values.

Do you mean something like this?

private List<T> UpdateValues<T>(T[] values)
{
   List<T> list = new List<T>();
   foreach(T t in values)
   {
      list.Add(t);
   }
   return list;
}

Then you have a list of T's which should be fairly easy to use. If that's not it can you elaborate the problem a little?

Ian
+2  A: 

Do you actually need the variables to be separate? Can you just use a collection of some form to start with - not as a copy, but to hold the data without any separate variables?

What were you doing with these variables in the repetitive code? You may find that you can get by with a convenience method instead of really looping.

Jon Skeet
A: 

You could try reflection,

Reflection.FieldInfo fields[] = this.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
Keivan