473,836 Members | 1,586 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can't assign value to structure in array?

I have created a structure with five fields. I then create an array of this
type of structure and place the structure into an array element. Say index
one. I want to assign a value to field3 of the structure inside the array.
When I try this, an error about late assignment appears. Is it possible to
assign a value to a structure field that is in an array?

I'm currently getting around the problem by creating a new structure, assign
the structure fields using values in the arary...minus field 3, which gets a
value from somewhere else. I then place this structure into the array.

Thanks,
Brett
Nov 17 '05
26 7104
That error message is a big red flag telling you that this should not be a
struct, but should be a class instead. There's very little reason to use
structs in .Net programming -- use them only when you need a new thing
that's treated and manipulated immutably.

"Brett" <no@spam.com> wrote in message
news:%2******** *******@TK2MSFT NGP15.phx.gbl.. .
I have created a structure with five fields. I then create an array of
this type of structure and place the structure into an array element. Say
index one. I want to assign a value to field3 of the structure inside the
array. When I try this, an error about late assignment appears. Is it
possible to assign a value to a structure field that is in an array?

I'm currently getting around the problem by creating a new structure,
assign the structure fields using values in the arary...minus field 3,
which gets a value from somewhere else. I then place this structure into
the array.

Thanks,
Brett

Nov 17 '05 #11
It is an arraylist and not an array so what you have said makes sense. Ok,
a couple have suggested this should possibly be a class. I still don't get
why people are saying the thing I'm doing is a red flag. I'm trying to
reassign values to structure fields within one element of an array. I know
the particular element and the fields of the structure within that element.
So it isn't as if there are other areas in the program that are also
accessing this structure in the same arraylist element.

My flow goes like this:
1. create new structure and assign values
2. put structure into arraylist position (i.e. position 2)
3. new conditions have created values that need to be assigned to certain
structure fields in position two of the arraylist
4. loop through arraylist and assign structure values to a database

My point is that the structure is access only three times. Two writes and
one read. This isn't complicated and I don't have to worry about
accidentally assigning a value to the structure while it is being read
somewhere else. That can't happen since the flow is procedural. I believe
that is the red flag some of you were thinking about.

Please elaborate on the above of where I may be wrong or have
misinterpreted.

Thanks,
Brett

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
Note that it makes a big difference whether it is an array:

MyStruct arr = new MyStruct[15];

...or a collection:

ArrayList arr = new ArrayList();
arr.Add(new MyStruct());
...etc.

In the first case, as Jon pointed out, .NET stores the array of a
contiguous chunk of memory containing the values for all of the
structs. In the second case, the structs are boxed and references to
the structs are stored in the ArrayList.

In the first case you can do things like

arr[9].Property = 5;

and it works. In the second case, you can't, because the struct must be
boxed when it's put in the ArrayList, and unboxed when it's removed, so
you only ever get a copy back.

As Jonathan pointed out, structs should, in general, be immutable. To
change a value in a struct you should construct a new one using values
from the old one (except for the value you want to change). Creating
mutable structs is just asking for trouble. In fact, if you're creating
a mutable struct, it begs the question of why you made it a struct to
start with. Why isn't it a class?

Nov 17 '05 #12

"Brett" <no@spam.com> wrote in message
news:uV******** ******@TK2MSFTN GP14.phx.gbl...
<snip>
My point is that the structure is access only three times. Two writes and
one read. This isn't complicated and I don't have to worry about
accidentally assigning a value to the structure while it is being read
somewhere else. That can't happen since the flow is procedural. I
believe that is the red flag some of you were thinking about.


SO....Why are you making it a struct?

If you make it a class instead it will work.

Bill
Nov 17 '05 #13
Actually mutable structs are very useful. It is inefficient or inconvenient
at times to copy all fields from the old struct, instead of simply changing
one field. The confusion stems from the fact that C# does not distinguish in
any way between value type and reference type modifications. But the
compiler does catch attempts to modify a temporary struct returned from an
indexer.

For example, if you have a struct with 6 32-bit fields, and you wish to
change one field in each struct in a large array, only a mutable struct will
allow you to do this efficiently. A class would add heap overhead and an
extra pointer dereference.

Regards,
Frank Hileman

check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio .NET graphics editor

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
As Jonathan pointed out, structs should, in general, be immutable. To
change a value in a struct you should construct a new one using values
from the old one (except for the value you want to change). Creating
mutable structs is just asking for trouble. In fact, if you're creating
a mutable struct, it begs the question of why you made it a struct to
start with. Why isn't it a class?

Nov 17 '05 #14
> For example, if you have a struct with 6 32-bit fields, and you wish to
change one field in each struct in a large array, only a mutable struct
will allow you to do this efficiently. A class would add heap overhead and
an extra pointer dereference.
I don't believe that. How can the pointer dereference have such a
significant cost that it alone determines whether or not whole program is
efficient? If you are really to the point where that is your bottleneck, its
time to drop C# and go to a lower-level language.

--
Jonathan Allen
"Frank Hileman" <fr******@no.sp amming.prodiges oftware.com> wrote in message
news:u0******** ******@TK2MSFTN GP10.phx.gbl... Actually mutable structs are very useful. It is inefficient or
inconvenient at times to copy all fields from the old struct, instead of
simply changing one field. The confusion stems from the fact that C# does
not distinguish in any way between value type and reference type
modifications. But the compiler does catch attempts to modify a temporary
struct returned from an indexer.

For example, if you have a struct with 6 32-bit fields, and you wish to
change one field in each struct in a large array, only a mutable struct
will allow you to do this efficiently. A class would add heap overhead and
an extra pointer dereference.

Regards,
Frank Hileman

check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio .NET graphics editor

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
As Jonathan pointed out, structs should, in general, be immutable. To
change a value in a struct you should construct a new one using values
from the old one (except for the value you want to change). Creating
mutable structs is just asking for trouble. In fact, if you're creating
a mutable struct, it begs the question of why you made it a struct to
start with. Why isn't it a class?


Nov 17 '05 #15
?? Every pointer dereference, every instruction, counts in a tight loop. The
lack of user-defined value types in Java (structs in C#) was a deficiency
for high performance applications, both in space (memory) and time. Struct
was added to C# for good reasons.

C# is fine for high performance applications, and we can assume it will get
better over time, especially with regards to structs.

Regards,
Frank Hileman

"Jonathan Allen" <x@x.x> wrote in message
news:Oj******** ******@TK2MSFTN GP14.phx.gbl...
For example, if you have a struct with 6 32-bit fields, and you wish to
change one field in each struct in a large array, only a mutable struct
will allow you to do this efficiently. A class would add heap overhead
and an extra pointer dereference.


I don't believe that. How can the pointer dereference have such a
significant cost that it alone determines whether or not whole program is
efficient? If you are really to the point where that is your bottleneck,
its time to drop C# and go to a lower-level language.

Nov 17 '05 #16
> ?? Every pointer dereference, every instruction, counts in a tight loop

Not true. If the loop isn't the bottleneck in your application, it doesn't
matter what is going on in it.

Honestly, can you think of a single time in your entire life that an extra
dereference in a loop actually made the difference between a usable and
unusable program?

Another consideration is what you are going to do with your N structs. Will
they really live solely in that array? Are you never going to sort it? Are
you never going to return a subset from a function call?

I'm asking because the first time you copy those structs to another
location, you've already lost your gain several times over. Copying a struct
is far more expensive than copying a pointer.

--
Jonathan Allen
"Frank Hileman" <fr******@no.sp amming.prodiges oftware.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
?? Every pointer dereference, every instruction, counts in a tight loop.
The lack of user-defined value types in Java (structs in C#) was a
deficiency for high performance applications, both in space (memory) and
time. Struct was added to C# for good reasons.

C# is fine for high performance applications, and we can assume it will
get better over time, especially with regards to structs.

Regards,
Frank Hileman

"Jonathan Allen" <x@x.x> wrote in message
news:Oj******** ******@TK2MSFTN GP14.phx.gbl...
For example, if you have a struct with 6 32-bit fields, and you wish to
change one field in each struct in a large array, only a mutable struct
will allow you to do this efficiently. A class would add heap overhead
and an extra pointer dereference.


I don't believe that. How can the pointer dereference have such a
significant cost that it alone determines whether or not whole program is
efficient? If you are really to the point where that is your bottleneck,
its time to drop C# and go to a lower-level language.


Nov 17 '05 #17

"Jonathan Allen" <x@x.x> wrote in message
news:OZ******** ******@TK2MSFTN GP10.phx.gbl...
?? Every pointer dereference, every instruction, counts in a tight loop
Not true. If the loop isn't the bottleneck in your application, it doesn't
matter what is going on in it.

Honestly, can you think of a single time in your entire life that an extra
dereference in a loop actually made the difference between a usable and
unusable program?


What do you mean by dereferencing the struct?

Another consideration is what you are going to do with your N structs.
Will they really live solely in that array? Are you never going to sort
it? Are you never going to return a subset from a function call?
What do you mean by returning a subset from a function?

I'm asking because the first time you copy those structs to another
location, you've already lost your gain several times over. Copying a
struct is far more expensive than copying a pointer.


And this is why the class should be used over a struct?

Should a struct ever be used verses a class?

Nov 17 '05 #18
If a loop is not a bottleneck -- why discuss performance? Let us assume the
developer can determine bottlenecks.

Yes, a single pointer dereference has made a critical difference in code I
have written. This type of code is common in graphics libraries, mathematics
libraries, processing huge data sets, scientific applications, collection
libraries, etc.

The increased memory usage of an array of object references (8 bytes heap
overhead per object + 4 bytes per array element pointer) decreases locality
of reference, which also impacts performance. Consider an 8 byte struct.
Substitute a class, and you have increased memory usage by 150%. If you have
an array with 100K elements, the struct version uses 800K bytes, and the
object version uses 2 meg. These types of differences can push you out of a
fast cache limit.

Structs in arrays can be sorted. If a struct is the same size as a pointer,
it is the same cost to copy. If used improperly large structs can be a
problem, but that is no reason to ban mutable structs. A better approach
would be to fix the language, so that a struct copy can be easily
distinguished from a reference (pointer) copy, reducing confusion.

Consider a struct with 8 properties, each internally consuming one byte of
storage. Suppose you need to modify one property. If the struct is
immutable, you must "modify" it by copying all 8 property values to a
constructor for a new struct taking 8 arguments. If the struct is mutable
the code is much simpler -- just change the property. So it is not just a
performance argument.

Frank

"Jonathan Allen" <x@x.x> wrote in message
news:OZ******** ******@TK2MSFTN GP10.phx.gbl...
?? Every pointer dereference, every instruction, counts in a tight loop


Not true. If the loop isn't the bottleneck in your application, it doesn't
matter what is going on in it.

Honestly, can you think of a single time in your entire life that an extra
dereference in a loop actually made the difference between a usable and
unusable program?

Another consideration is what you are going to do with your N structs.
Will they really live solely in that array? Are you never going to sort
it? Are you never going to return a subset from a function call?

I'm asking because the first time you copy those structs to another
location, you've already lost your gain several times over. Copying a
struct is far more expensive than copying a pointer.

--
Jonathan Allen

Nov 17 '05 #19
"Brett" <no@spam.com> wrote in message
news:%2******** *******@TK2MSFT NGP15.phx.gbl.. .
What do you mean by dereferencing the struct?
Internally, when you access an array element, if the array element contains
a reference to an object (declared as a class, not a struct) and you access
a field via a property in that object, there are two pointer dereferences:
one to get the address of the array memory block, and one to get the addess
of the field within the object.

By contrast, a struct is stored within the array memory block, so only one
pointer dereference is needed.

We are speaking at the level of the machine code. You cannot see this by
looking at the C# code, except by noticing what type of array you are
working with.

Should a struct ever be used verses a class?


If your abstraction already needs copy-by-value semantics, and it is not too
large, a struct is usually a better choice.

Consider a matrix class that overloads operator*. If you are overloading
operators, you probably want the return value to be a new matrix. In this
case, a struct makes perfect sense if the matrix is not too large and you
will be using lots of operators, as the struct is always passed by value,
and does not have the GC overhead that comes about from creating lots of
small objects.

The other reason for using a struct instead of a class is performance. Again
looking at a graphics package, a Point abstraction will consume less memory
and be faster as a struct, as the Point will typically be used in large
arrays.

We have found that a 6x2 float matrix is a better choice than an equivalent
class. This is larger than the usual choice for a struct, so it was
surprising.
Regards,
Frank Hileman

check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio .NET graphics editor
Nov 17 '05 #20

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

Similar topics

6
644
by: Ram Laxman | last post by:
Hi all, Can I assign an array to a vector if both(array and vector) holds same data type?
7
6631
by: baumann | last post by:
hi all, #include "stdafx.h" struct a_{ int a; int b; };
0
1802
by: JJ_377 | last post by:
The following doesn't assign value to the dropdownlist - WHY? ___________________________________________________________________ In a user control (ascx named USACustomer) : Public Property State() As String Get Return Me.ddlState.SelectedValue End Get Set(ByVal Value As String)
7
2047
vikas251074
by: vikas251074 | last post by:
Can I assign value to cookies immediately after selecting a value from list? <select name="vlan_name" style="width:150px "> <%set rs = conn.execute("select vlan_name from vlan_master order by vlan_name") dim v_lan do while not rs.eof%> <option value="<%=rs("vlan_name")%>"><%=rs("vlan_name")%></option> <% rs.movenext loop%> </select>
17
9623
by: zombiezoom | last post by:
I need help with error 2448: You can't assign value to this object. What I am trying to do is allow user to select event id and race id from combo option. Once the user selects those, then the id associated with those is suppose to be carried over to a new form which should associated those two ids with runner id from runner table. Thus, I will have all three ids in event-race-runner table (which is an associative table). However when I do that...
0
9820
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10846
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...
0
10551
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10594
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
9376
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...
0
6979
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5828
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3116
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.