Andrew McCafferty
Andrew McCafferty

Reputation:

C# Private variable list

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?

Upvotes: 0

Views: 2460

Answers (4)

kay.one
kay.one

Reputation: 7692

You could try reflection,

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500515

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.

Upvotes: 2

Ian
Ian

Reputation: 34489

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?

Upvotes: 0

Sam Harwell
Sam Harwell

Reputation: 99869

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

Upvotes: 0

Related Questions