473,785 Members | 2,282 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning an array in a property get returns a copy. How to get a reference?

Hi,

The following code is from an article published in Informit.com at
http://www.informit.com/guides/conte...net&seqNum=142. The problem
is the author says it is not a good idea to return an array as a property
because it will return a copy of the array instead a reference to it. How
can I force the property to return a reference to the array? Is it only a
feature of arrays? I hope normal class objects (including collections) are
returned by reference in the same situation.

Well, I'll be glad to hear about workarounds to this array problem.
Thanks in advance
Faustino

The code follows:

class GameThing
{
private readonly int[] scoreValues = new int[22];

public GameThing()
{
for (int i = 0; i < scoreValues.Len gth; i++)
{
scoreValues[i] = scoreValues.Len gth - i - 1;
}
}

public int[] Values
{
get { return scoreValues; }
}
}
Nov 16 '05 #1
3 2700
System.Array is a reference type, so therefore the only copy that is taking
place
is copying the address to the reference(32 bits).

System.Int32 itself is a value type, but an array(or any type of array FTM)
of System.Int32 is not.
Retrieving specific items in an array of value types though, will create a
copy of that value.
But anyway, you do not lose anything, since an Int32 and a pointer to an
Int32 are of the same size.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Faustino Dina" <ff****@matusa. com.mx> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
Hi,

The following code is from an article published in Informit.com at
http://www.informit.com/guides/conte...net&seqNum=142. The
problem
is the author says it is not a good idea to return an array as a property
because it will return a copy of the array instead a reference to it. How
can I force the property to return a reference to the array? Is it only a
feature of arrays? I hope normal class objects (including collections) are
returned by reference in the same situation.

Well, I'll be glad to hear about workarounds to this array problem.
Thanks in advance
Faustino

The code follows:

class GameThing
{
private readonly int[] scoreValues = new int[22];

public GameThing()
{
for (int i = 0; i < scoreValues.Len gth; i++)
{
scoreValues[i] = scoreValues.Len gth - i - 1;
}
}

public int[] Values
{
get { return scoreValues; }
}
}

Nov 16 '05 #2
Faustino Dina <ff****@matusa. com.mx> wrote:
The following code is from an article published in Informit.com at
http://www.informit.com/guides/conte...net&seqNum=142. The problem
is the author says it is not a good idea to return an array as a property
because it will return a copy of the array instead a reference to it.
How can I force the property to return a reference to the array?


The author is talking rubbish. It's returning a reference. I do wish
people who had no idea what they're talking about didn't write articles
on those topics :(

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #3
I think that the author was trying to point out some of the pitfalls of
returning arrays from properties or methods, but got confused and ended
up, as you said, "talking rubbish."

First of all, as Jon pointed out, returning arrays from properties or
methods returns a reference, not a copy of the array. Most newbies
return arrays from properties or methods without giving it a second
thought. I know I did until FxCop pointed out that this was a dangerous
practice. Unfortunately, there is no simple, satisfactory solution to
the following problems.

If the array you're returning forms part of your object's state (which
it probably does), you're giving your caller a reference directly to
part of your internal state. This means that, after the caller has the
array, any changes the object later makes to its internal state will be
immediately reflected in the array that the caller is holding (because
it's the same array that the object is using to maintain state).

So, I call your object to, say, get a list of all of the newsgroups to
which I'm subscribed. I store that array away somewhere for later
reference. I then subscribe to a new newsgroup. Lo and behold, the new
newsgroup appears in the array that I got from the object "way back
when"! How come the array I'm holding changed magically without my
touching it? Because the object and I are sharing the same array, so an
internal change becomes an external change as well. This can lead to
nasty and subtle bugs.

Worse still, what if I decide to perform some destructive operation on
the array? After all, the object gave it to me, it's mine, so why can't
I change it? The answer is that if I change it then I'm changing the
object's internal state, since we both have references to the same
array. The object could then crash horribly because somebody messed
with its internal state directly, without going through its methods and
properties that safeguard that state. So much for encapsulation!

If you think that copying the array on return from a property or method
solves these problems, it does, but at the cost of introducing new
problems. In order to fix the above, you return a copy, not the
original array. Now your object's internal state is safe, but your
caller can do innocent things like this:

for (int i = 0; i < obj.ArrayCopyPr operty.Length; i++)
{
.... do something with obj.ArrayCopyPr operty[i] ...
}

Each trip around the loop copies the array twice: the first time it
copies the array just to get its length, the second time just to pick
up element "i". If the array has 1,000,000 elements then you will
create and throw away 2,000,000 arrays in order to do this operation.
Ouch!

There are solutions that solve all of these problems, but they are
quite complex. For now, just be aware that returning an array reference
to a caller, while it's the simplest solution, comes with some dangers.

Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2875
by: Nico | last post by:
Hello folks, I am currently storing a set of objects inside an array, $itemlist = array(); $itemlist = new item("myitem"); //... and I am looking to develop a search function, which returns a reference to the found item.
6
14034
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return value of a function acts like 'by Val' returning the value only (except for objects) can you make it return a reference instead? cheers, Krackers
8
10232
by: Mike S. Nowostawsky | last post by:
I tried using the "toUpperCase()" property to change the value of an array entity to uppercase BUT it tells me that the property is invalid. It seems that an array is not considered an object when it is assigned a text literal?? HOW can I change the array value to upper case then? What other method exists for arrays? Ex: var GridArrayName1 = new Array(); GridArrayName1 = new Array ('test-value'); GridArrayName1 = GridArrayName1...
11
1946
by: JKop | last post by:
AnyClass Blah() { AnyClass poo; return poo; } As we all know, in the above, the compiler is entitled to:
2
2103
by: Cory Burkhardt | last post by:
I am not sure what the suggested practice is for returning reference types from read-only properties. Consider an example: Suppose I have a Point class that is a reference type. I use the Point class from within a Shape class. I want the user of the Shape class to be able to see the location of the Shape but not be able to change it. So I declare a read-only property: class Shape { private Point location; /* other Shape stuff */
5
9065
by: Naveen Mukkelli | last post by:
Hi, I've got a property that returns byte. For example, private byte bytes; public byte ReturnsByteArray { get
5
2653
by: Sam | last post by:
Hi All I have couple of question regarding property of a class and structures. **** ---- Here is my class and structure ---- ***** 1. Public Structure MyPoint 2. Dim p As Point 3. Dim ptColor As Color 4. End Structure
17
3264
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
5
2682
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
10350
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10097
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9957
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8983
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7505
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.