Click here to Skip to main content
15,893,381 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a program I hve to return a multi-dimensional array, so that I could use it in another class.
One solution is declaring that array as static...
Another way is to declare a property which through GET-SET Property returns the array through its GET property...

When I am doing so the compiler is giving me warning that -- property shouldn't return arrays...Why...?

What I have tried:

Declared in Child Class....
public string[,,,] Fields
{
get { return row;}
}
row is the multi-dimensional array....
Posted
Updated 10-Jul-20 5:22am

 
Share this answer
 
Start with the error message documentation:
CA1819: Properties should not return arrays - Visual Studio | Microsoft Docs[^]
It explains:
Microsoft:
Arrays returned by properties are not write-protected, even if the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users won't understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.

Copying an array is a big job, and can cause quite a performance hit, which is hidden in an innocuous line
C#
for (int x = 0; x < myVar.Array.Width; x++)
   for (int y = 0; y < myVarArray.Height; y++)
      Console.WriteLine(myVar.Array[x,y]);
Looks like perfectly good code, but each access to the Array creates a new copy of the original.

Instead of an Array, use a List or similar collection.
 
Share this answer
 
Comments
[no name] 10-Jul-20 11:30am    
Can you give me a hint, why List instead of array should help? In my opinion also returning a List does not prevent from modify it. Where I'm wrong?
Thank you in advance.
OriginalGriff 10-Jul-20 11:40am    
I absolutely agree - returning a List is just as bad, but ... that's MS for you.
Returning any collection is something to think about carefully, and probably to provide a method for instead of a property because it "hides" the copy operation a bit less.
You only get the error if the property is externally visible, so ...
Member 12712527 10-Jul-20 11:52am    
Sir you're saying Lists are also bad. Is it viable to use static array or what will be the right solution....?
CHill60 10-Jul-20 11:57am    
Provide a method rather than using a property
[no name] 10-Jul-20 12:02pm    
I would say derive from Array or List and define an read-only interface (to return) is the 'correct' solution, but most probably overkill.

And also this does finally not prevent from casting the return value and modify it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900