Javier
Javier

Reputation: 11

Initializing an array based on the present values

I want to initialize an c# array. I don't know in advance how many values I am going to store on it. I know that this number will be between 0 and 5.

Is this the best approach to do this?

private CompiledRuleMethod CompileRuleMethod(Rule r)
{
  int sizeParameters = 0;
  if (r.Param1 != "") sizeParameters++;
  if (r.Param2 != "") sizeParameters++;
  if (r.Param3 != "") sizeParameters++;
  if (r.Param4 != "") sizeParameters++;
  if (r.Param5 != "") sizeParameters++;
  object[] parameters = new object[sizeParameters];
  if (r.Param1 != "") parameters[0] = r.Param1;
  if (r.Param2 != "") parameters[1] = r.Param2;
  if (r.Param3 != "") parameters[2] = r.Param3;
  if (r.Param4 != "") parameters[3] = r.Param4;
  if (r.Param5 != "") parameters[4] = r.Param5;

  return new CompiledRuleMethod(DelegateFactory.Create(typeof(RuleMethod).GetMethod(r.MethodName)),parameters);
}

I am pretty sure that isn't.

Upvotes: 0

Views: 53

Answers (2)

Sweeper
Sweeper

Reputation: 273898

Note that your current code doesn't actually work. If, say, only Param4 is empty, then sizeParameters is 4. And then you create a parameters array of length 4. However, when the execution reaches the last line, it will try to put Param5 into index 4 of the array, causing an IndexOutofRangeException.

It seems like you just want to filter out those params that are empty, and keep the ones that are not empty.

You can first put all of the params you want into an array:

var unfilteredParams = new[] {r.Param1, r.Param2, r.Param3, r.Param4, r.Param5};

And then use Where to filter it:

var filteredParams = unfilteredParams.Where(x => x != "").ToArray();

Upvotes: 1

see sharper
see sharper

Reputation: 12055

Don't use an array. List is more appropriate if you don't know how many items it will need. Then you can use list.Add(r.Param) to append items. Though without more context it's hard to say what is the best approach.

Upvotes: 0

Related Questions