11

While I try to resize an array in C# as below,

Array.Resize(ref Globals.NameList, 0);

I get the below error

A property or indexer may not be passed as an out or ref parameter

Globals is an object. NameList is a string type array declared in Globals Class.

Please help me to fix this by posting the correct code.

Thanks!

codebug
  • 197
  • 1
  • 3
  • 15
  • Just a more information. Same error occur when we use a property as out parameter in int.TryParse(). In this case also we need a intermediate variable to do the operation. Then assign the variable's value to the property. – Narendra Aug 01 '12 at 12:27

3 Answers3

28

use variable, but not property

var obj = Globals.NameList;
Array.Resize(ref obj , 0);
Globals.NameList=obj;
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
10

The compiler error speaks for itself - you can't pass a property by reference; only a variable.

From the C# spec section 10.6.1.2:

When a formal parameter is a reference parameter, the corresponding argument in a method invocation must consist of the keyword ref followed by a variable-reference (section 5.3.3) of the same type as the formal parameter.

A property access expression doesn't count as a variable-reference.

You probably want:

var tmp = Globals.NameList;
Array.Reize(ref tmp, 0);
Globals.NameList = tmp;

Note that VB does allow passing a property by reference, but it acts like the above. In particular, each assignment within the method will only affect a temporary value, rather than being a call to the relevant setter.

Also note that having a class called Globals with mutable public properties is a design smell...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon Skeet. In case this is not a good approach, if I need to group few global variables and objects that should be made accessible to whole application what should be the best practice ? – codebug Aug 02 '12 at 03:59
  • Jon Skeet.. I cannot accept multiple post as answer ? Wanted to accept your comment also as an answer. Currently I cannot upvote your post at my level :) – codebug Aug 02 '12 at 04:06
  • 2
    @codebug: You can only accept one post, yes. Accept whichever is most helpful to you. As for the design - try to avoid *needing* "objects that should be made accessible to the whole application". Look into using dependency injection to allow each class to express what it needs. – Jon Skeet Aug 02 '12 at 05:58
0

do

Array arr = Globals.NameList;
Array.Resize(ref arr, 0);
Globals.NameList = arr;
codeteq
  • 1,502
  • 7
  • 13