473,705 Members | 2,472 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 #1
26 7086
Brett,

That's pretty much the way that you have to do it. It's the same
problem you would have if you were to return a structure from a property on
a class. Since a copy is returned, you have to store the copy, then
reassign it.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"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 #2
All structures should be immutable. If is it possible to change the
structure in any perceivable way, then chances are it will be used
incorrectly. For example, if you return the structure from a property, one
may think that changing the structure will change the class.

myClass.myStruc tProperty.myVal ue = 5;

this compiles as...

aStruct temp = myClass.myStruc tProperty;
temp.myValue = 5;
//throw away temp and its new value.


********

As for you specific problem, post the code.

--
Jonathan Allen
"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 #3
Ok, you confirmed that is the way to do it but why?. Why exactly can't I
assign values to the structure fields that are in the array but can when
they aren't in the array?

If it were just a simple array element I could assign a value.
Thanks,
Brett
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:ep******** ********@TK2MSF TNGP14.phx.gbl. ..
Brett,

That's pretty much the way that you have to do it. It's the same
problem you would have if you were to return a structure from a property
on a class. Since a copy is returned, you have to store the copy, then
reassign it.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"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 #4
Brett,

Here is the reason why. Say you have the following structure
declaration:

public struct MyStruct
{
public int MyInt;
}

Then you have this array:

// Create an array with three elements.
MyStruct[] structs = new MyStruct[3];

At that point, you have an array of three structures with MyInt values
of 0. Now when you do this:

// Assign MyInt on the first element of the array.
structs[0].MyInt = 2;

The statement structs[0] returns a copy of the element in the array, and
you end up setting the MyInt field on the copy, not the original.

Now, this should not give you a compiler error, but it's definitely not
behavior that you want. I am curious what the code is that is giving you
the error.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Brett" <no@spam.com> wrote in message
news:%2******** **********@TK2M SFTNGP15.phx.gb l...
Ok, you confirmed that is the way to do it but why?. Why exactly can't I
assign values to the structure fields that are in the array but can when
they aren't in the array?

If it were just a simple array element I could assign a value.
Thanks,
Brett
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote
in message news:ep******** ********@TK2MSF TNGP14.phx.gbl. ..
Brett,

That's pretty much the way that you have to do it. It's the same
problem you would have if you were to return a structure from a property
on a class. Since a copy is returned, you have to store the copy, then
reassign it.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"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 #5
Here's the code. It's in VB.NET but you can see well what is going on. I'm
converting to C# but wanted to get past this first.

For x As Integer = 0 To ParsedMessage.L ength - 1

'create space for new array element
ReDim Preserve imageMapInfoArr (x)

' copy into new structure
imageMapInfo.Ti ckCount_ = ParsedMessage(x ).TickCount_
imageMapInfo.Se rver_StatusCode = ParsedMessage(x ).Server_Status Code
imageMapInfo.UR LDestination = ParsedMessage(x ).URLDestinatio n
imageMapInfo.Im ageURLInSourceT ext = strImageMapImag e
imageMapInfo.UR LSourceType = "Image Map"
imageMapInfo.UR LSource = ParsedMessage(x ).URLSource
imageMapInfoArr (x) = imageMapInfo
Next

I can't do something like:
ParsedMessage(x ).URLSourceType = "Image Map"

That's why I'm doing it like the above.

Thanks,
Brett

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:u0******** *****@tk2msftng p13.phx.gbl...
Brett,

Here is the reason why. Say you have the following structure
declaration:

public struct MyStruct
{
public int MyInt;
}

Then you have this array:

// Create an array with three elements.
MyStruct[] structs = new MyStruct[3];

At that point, you have an array of three structures with MyInt values
of 0. Now when you do this:

// Assign MyInt on the first element of the array.
structs[0].MyInt = 2;

The statement structs[0] returns a copy of the element in the array,
and you end up setting the MyInt field on the copy, not the original.

Now, this should not give you a compiler error, but it's definitely not
behavior that you want. I am curious what the code is that is giving you
the error.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Brett" <no@spam.com> wrote in message
news:%2******** **********@TK2M SFTNGP15.phx.gb l...
Ok, you confirmed that is the way to do it but why?. Why exactly can't I
assign values to the structure fields that are in the array but can when
they aren't in the array?

If it were just a simple array element I could assign a value.
Thanks,
Brett
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote
in message news:ep******** ********@TK2MSF TNGP14.phx.gbl. ..
Brett,

That's pretty much the way that you have to do it. It's the same
problem you would have if you were to return a structure from a property
on a class. Since a copy is returned, you have to store the copy, then
reassign it.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"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 #6
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard .caspershouse.c om> wrote:
Here is the reason why. Say you have the following structure
declaration:

public struct MyStruct
{
public int MyInt;
}

Then you have this array:

// Create an array with three elements.
MyStruct[] structs = new MyStruct[3];

At that point, you have an array of three structures with MyInt values
of 0. Now when you do this:

// Assign MyInt on the first element of the array.
structs[0].MyInt = 2;

The statement structs[0] returns a copy of the element in the array, and
you end up setting the MyInt field on the copy, not the original.


That's not actually true. Try this, for example:

using System;
using System.Drawing;

class Test
{
static void Main()
{
Point[] p = new Point[50];
p[0].X=5;
Console.WriteLi ne (p[0]);
}
}

The result is:
{X=5,Y=0}

Arrays are treated as sets of variables, effectively - even the C#
language specification talks about them that way. Note that this is
very different from the behaviour you'd get if you were using an
indexer, or a property.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7
Brett <no@spam.com> wrote:
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?


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

Being in an array shouldn't be a problem in itself. Here's an example
of what it sounds like you're doing:

using System;
using System.Drawing;

struct Foo
{
public int Field1;
public int Field2;

public override string ToString()
{
return string.Format(" {0}/{1}", Field1, Field2);
}
}

class Test
{
static void Main()
{
Foo[] f = new Foo[10];
f[0].Field1=10;
f[1].Field2=5;

Console.WriteLi ne (f[0]);
Console.WriteLi ne (f[1]);
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
If the struct is small, you should post its code as well.
ReDim Preserve imageMapInfoArr (x)
Move this outside of the loop.

--
Jonathan Allen
"Brett" <no@spam.com> wrote in message
news:u$******** ******@TK2MSFTN GP09.phx.gbl... Here's the code. It's in VB.NET but you can see well what is going on.
I'm converting to C# but wanted to get past this first.

For x As Integer = 0 To ParsedMessage.L ength - 1

'create space for new array element
ReDim Preserve imageMapInfoArr (x)

' copy into new structure
imageMapInfo.Ti ckCount_ = ParsedMessage(x ).TickCount_
imageMapInfo.Se rver_StatusCode = ParsedMessage(x ).Server_Status Code
imageMapInfo.UR LDestination = ParsedMessage(x ).URLDestinatio n
imageMapInfo.Im ageURLInSourceT ext = strImageMapImag e
imageMapInfo.UR LSourceType = "Image Map"
imageMapInfo.UR LSource = ParsedMessage(x ).URLSource
imageMapInfoArr (x) = imageMapInfo
Next

I can't do something like:
ParsedMessage(x ).URLSourceType = "Image Map"

That's why I'm doing it like the above.

Thanks,
Brett

Nov 17 '05 #9
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 #10

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
6629
by: baumann | last post by:
hi all, #include "stdafx.h" struct a_{ int a; int b; };
0
1791
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
2038
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
9608
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
8767
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
8689
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
9273
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
8979
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
7893
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
5933
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
4703
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3137
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2486
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.