Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A property or indexer may not be passed as an out or ref parameter while Array Resize [duplicate]

Tags:

c#

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!

like image 283
codebug Avatar asked Aug 01 '12 12:08

codebug


2 Answers

use variable, but not property

var obj = Globals.NameList;
Array.Resize(ref obj , 0);
Globals.NameList=obj;
like image 107
burning_LEGION Avatar answered Nov 10 '22 18:11

burning_LEGION


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...

like image 21
Jon Skeet Avatar answered Nov 10 '22 18:11

Jon Skeet