473,411 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,411 software developers and data experts.

Struct that contains an array?

Hello!

I have these following classes:

public struct Move
{
public int From { get; set; }

public int To { get; set; }

public int Captures { get; set; }
}

public class MoveList
{
private Move[] moves = new Move[32];

public int Length { get; private set; }

public void Add(Move move)
{
moves[Length++] = move;
}

public Move this[int index]
{
get
{
return moves[index];
}
}
}

MoveList seems to be a candidate for being a struct. However, I can't seem
to create a struct that contains an array. Is this possible? If so, how does
one do it?

Thanks in advance!

--
Daniel

Aug 19 '08 #1
16 2347
There is nothing special about creating a struct with an array - it
should work fine "as is" - however, I disagree that MoveList would
make a good struct - the Add() etc suggest mutablitly, which is
*always* a bad idea in a struct; in particular, the expectation with a
struct is that it has value-type semantics, but the presence of a
mutable array would bind two isolated structs together in unexpected
ways.

Actually, it is /incredibly/ rare to (correctly) create a struct
in .NET; just leave it as a class... you should only create structs
for (immutable) "value units", for example a "currency
value" (immutably combining a decimal and a currency code), or a "time
range" (immutably combining either 2 DateTimes, or a DateTime and
TimeSpan).

Marc
Aug 19 '08 #2
On Aug 19, 8:50*am, Daniel Lidström <some...@microsoft.comwrote:
I have these following classes:

* *public struct Move
* *{
* * * public int From { get; set; }

* * * public int To { get; set; }

* * * public int Captures { get; set; }
* *}
Mutable structs are really bad news. I suggest you either make this a
class, or make it immutable.
* *public class MoveList
* *{
* * * private Move[] moves = new Move[32];

* * * public int Length { get; private set; }

* * * public void Add(Move move)
* * * {
* * * * *moves[Length++] = move;
* * * }

* * * public Move this[int index]
* * * {
* * * * *get
* * * * *{
* * * * * * return moves[index];
* * * * *}
* * * }
* *}

MoveList seems to be a candidate for being a struct.
Not to me - again, it's mutable. Why would you particularly want it to
be a struct?
However, I can't seem
to create a struct that contains an array.
I don't see why not. You just can't use an instance initializer.
Is this possible? If so, how does one do it?
Well, you'd need to realise that there's no way of stopping "moves"
from being null - structs always have a default constructor, which
just sets all fields to default values (i.e. null in this case).
You could make the array lazily allocated (when fetching or adding)
but really I'm not convinced this should be a struct in the first
place.

Jon
Aug 19 '08 #3
Oh, by the way: Move should also be a class, or should be made
immutable; for example, the following Move would be OK as a struct
(although I'd still question why it isn't simply a class):

public struct Move
{
private readonly int from, to, captues;
public int From { get {return from;}}
public int To { get {return to;}}
public int Captures { get {return captues;}}
public Move(int from, int to, int captures)
{
this.from = from;
this.to = to;
this.captures = captures;
}
}

(again, I still think this looks more like a class than a struct - it
isn't a "measure", which is the most common struct scenario).

Marc
Aug 19 '08 #4
On Aug 19, 12:50*pm, Daniel Lidström <some...@microsoft.comwrote:
Hello!

I have these following classes:

* *public struct Move
* *{
* * * public int From { get; set; }

* * * public int To { get; set; }

* * * public int Captures { get; set; }
* *}

* *public class MoveList
* *{
* * * private Move[] moves = new Move[32];

* * * public int Length { get; private set; }

* * * public void Add(Move move)
* * * {
* * * * *moves[Length++] = move;
* * * }

* * * public Move this[int index]
* * * {
* * * * *get
* * * * *{
* * * * * * return moves[index];
* * * * *}
* * * }
* *}

MoveList seems to be a candidate for being a struct. However, I can't seem
to create a struct that contains an array. Is this possible? If so, how does
one do it?

Thanks in advance!

--
Daniel

MoveList is a structure containing array if Moves... check the
following code.

public struct Move
{
public int From { get; set; }

public int To { get; set; }

public int Captures { get; set; }
}

public struct MoveList
{
private Move[] moves;
public int Length { get; private set; }

public void Add(Move move)
{
if (moves == null)
moves = new Move[32];
moves[Length++] = move;
}

public Move this[int index]
{
get
{
if (Length < index)
throw new Exception("Index out of range");

return moves[index];
}
}
}
static void Main(string[] args)
{
Move m = new Move();
MoveList list = new MoveList();
list.Add(m);

Console.ReadLine();

}

-Cnu
Aug 19 '08 #5
On Aug 19, 1:20*pm, Duggi <DuggiSrinivasa...@gmail.comwrote:
On Aug 19, 12:50*pm, Daniel Lidström <some...@microsoft.comwrote:


Hello!
I have these following classes:
* *public struct Move
* *{
* * * public int From { get; set; }
* * * public int To { get; set; }
* * * public int Captures { get; set; }
* *}
* *public class MoveList
* *{
* * * private Move[] moves = new Move[32];
* * * public int Length { get; private set; }
* * * public void Add(Move move)
* * * {
* * * * *moves[Length++] = move;
* * * }
* * * public Move this[int index]
* * * {
* * * * *get
* * * * *{
* * * * * * return moves[index];
* * * * *}
* * * }
* *}
MoveList seems to be a candidate for being a struct. However, I can't seem
to create a struct that contains an array. Is this possible? If so, howdoes
one do it?
Thanks in advance!
--
Daniel

MoveList is a structure containing array if Moves... check the
following code.

public struct Move
* * * * {
* * * * * * public int From { get; set; }

* * * * * * public int To { get; set; }

* * * * * * public int Captures { get; set; }
* * * * }

* * * * public struct MoveList
* * * * {
* * * * * * private Move[] moves;
* * * * * * public int Length { get; private set; }

* * * * * * public void Add(Move move)
* * * * * * {
* * * * * * * * if (moves == null)
* * * * * * * * * * moves = new Move[32];
* * * * * * * * moves[Length++] = move;
* * * * * * }

* * * * * * public Move this[int index]
* * * * * * {
* * * * * * * * get
* * * * * * * * {
* * * * * * * * * * if (Length < index)
* * * * * * * * * * * * throw new Exception("Index out of range");

* * * * * * * * * * return moves[index];
* * * * * * * * }
* * * * * * }
* * * * }

* * * * static void Main(string[] args)
* * * * {
* * * * * * Move m = new Move();
* * * * * * MoveList list = new MoveList();
* * * * * * list.Add(m);

* * * * * * Console.ReadLine();

* * * * }

-Cnu- Hide quoted text -

- Show quoted text -
As replied by others, for me also, makeing Movelist as a struct does
not make sense. Still If you want to make it...above is the code
snippet...
-Cnu.
Aug 19 '08 #6
Daniel Lidström wrote:
Hello!

I have these following classes:

public struct Move
{
public int From { get; set; }

public int To { get; set; }

public int Captures { get; set; }
}

public class MoveList
{
private Move[] moves = new Move[32];

public int Length { get; private set; }

public void Add(Move move)
{
moves[Length++] = move;
}

public Move this[int index]
{
get
{
return moves[index];
}
}
}

MoveList seems to be a candidate for being a struct. However, I can't
seem to create a struct that contains an array. Is this possible? If so,
how does one do it?

Thanks in advance!
No, the MoveList class should definitely not be a struct. It can be
rewritten to work as a struct, but then it doesn't work properly.
Consider this example:

MoveList first = new MoveList();
MoveList second = first;
first.Add(new Move() { From = 1, To = 10, Captures = 2 });
first.Add(new Move() { From = 2, To = 3, Captures = 0 });
second.Add(new Move() { From = 12, To = 14, Captures = 1 });

Now you have two separate lists that share the same array. The first
list thinks that the array has two items, and the second list thinks
that the array has one item. When you added the item to the second list,
it did overwrite the first item that you added to the first list.

--
Göran Andersson
_____
http://www.guffa.com
Aug 19 '08 #7
check the following code.

While that might work for this sample, creating a mutable struct is a
really, really bad idea...

In this case, why not simply use a List<Move>?

Marc
Aug 19 '08 #8
and when I say "work for this sample", I mean that exact Main() - any
other use that uses the list as a variable, argument, etc - is going
to break very badly; the Length won't get carried, nor will array
creations - but if the array has already been created (by a previous
Add) we could be overwriting data from different calls (i.e. same
array, different Length). I can post some code illustrating this if
you want...

Marc
Aug 19 '08 #9
Now you have two separate lists that share the same array.

Actually I suspect you need to add an item (between "first = " and
"second = ") to initialize the array,, otherwise the first Add on each
creates a separate array - but I was about to post something
alarmingly similar ;-p

Marc
Aug 19 '08 #10
Thanks to all who replied, convincing me that I really should use classes
:-)

I was actually trying to explore what kind of performance I would get from
using value types instead of reference types. Has anyone here done any
testing with unsafe types, to measure performance gains?

--
Daniel

Aug 19 '08 #11
I was actually trying to explore what kind of performance I would get from
using value types instead of reference types. Has anyone here done any
testing with unsafe types, to measure performance gains?
Any performance difference would /generally/ be very small, and highly
dependent on your exact usage. It is incorrect to simply state, for
example "structs are quicker". There are a few *very specific*
scenarios in which struct access might be slighlty quicker due mainly
to not having to de-reference; however, an over-sized struct can have
a negative performance impact as it gets copied around the stack etc
(rather than a reference which takes a relatively small space).
Likewise, if you are only reading data you might be OK, but if you
need to make lots of changes then the intended immutable behavior of
structs may force you to do a lot more work to achieve a simple
update.

"unsafe" is something else again...

In most cases, the de-reference is not a bottleneck. Profile your code
and look for actual problems, otherwise you are doing premature
optimisation: your time could be spent better optimising the actual
problem (in fact, without profiling you are just as likely to make
things worse than better).

Marc
Aug 19 '08 #12
On Aug 19, 2:01*pm, Daniel Lidström <some...@microsoft.comwrote:
Thanks to all who replied, convincing me that I really should use classes
:-)

I was actually trying to explore what kind of performance I would get from
using value types instead of reference types. Has anyone here done any
testing with unsafe types, to measure performance gains?

--
Daniel
My simple suggestion would be, if the size of array is small, go for
struct or else classes are good idea. Also the frequency at which
application access the array also matters :-)

-Cnu.
Aug 19 '08 #13
On Aug 19, 11:39*am, Duggi <DuggiSrinivasa...@gmail.comwrote:
My simple suggestion would be, if the size of array is small, go for
struct or else classes are good idea.
Why? The array itself isn't going to be copied around - it's going to
be a reference either way, unless you use unsafe code and "fixed".
Also the frequency at which
application access the array also matters :-)
More important, IMO, is the maintainability of the code. Micro-
optimisation like this is unlikely to have a significant impact on
performance, but will almost certainly make the code harder to
maintain.

Jon
Aug 19 '08 #14
if the size of array is small, go for struct or else classes are good
idea.
That really has very little to do with the choice between struct and class.

As an aside, the size of structs *is* a factor, but arrays are always
allocated on the heap - MoveList (as a struct) would only contain a
reference (fixed size) to the array, not the array itself.

Marc
Aug 19 '08 #15
Marc Gravell wrote:
>Now you have two separate lists that share the same array.

Actually I suspect you need to add an item (between "first = " and
"second = ") to initialize the array,, otherwise the first Add on each
creates a separate array - but I was about to post something
alarmingly similar ;-p

Marc
Yes, you are correct, as the struct probably needs lazy initialisation
of the array to work at all.

--
Göran Andersson
_____
http://www.guffa.com
Aug 19 '08 #16
On Aug 19, 3:51*pm, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On Aug 19, 11:39*am, Duggi <DuggiSrinivasa...@gmail.comwrote:
My simple suggestion would be, if the size of array is small, go for
struct or else classes are good idea.

Why? The array itself isn't going to be copied around - it's going to
be a reference either way, unless you use unsafe code and "fixed".
Also the frequency at which
application access the array also matters :-)

More important, IMO, is the maintainability of the code. Micro-
optimisation like this is unlikely to have a significant impact on
performance, but will almost certainly make the code harder to
maintain.

Jon
Thanks to Jon and thanks to Marc

I was under a wrong perception. I agree size should not matter here.
And I agree with your opinion about the code maintainability also.

-Cnu
Aug 20 '08 #17

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

Similar topics

7
by: seia0106 | last post by:
Hello, Writing a program in c++ that should use complex numbers I have two choices before me. 1- define a struct for complex data i.e struct {float real,imag; }ComplexNum; 2-use an array...
10
by: David Rasmussen | last post by:
If I have this struct S { int arr; }; and I do this: S s1,s2;
3
by: Olav Langeland | last post by:
I am reading data to/from a file which contains C++ structures like this struct StructCPP { long lDgType; FILETIME ftDgTime; char cName; char cVersion; char cSpare; long lCount;
3
by: Rudy Velthuis | last post by:
Hello, Does anyone know how to create a struct that will marshal to the following C++ struct A, containing an array of the user defined String10 type: struct String10 { char SLen; char S;
1
by: VMI | last post by:
How can I convert this struct into a C# struct? The problem with this one is that one of its members is an array of ADDR_REC(another struct), and the API function (written in C) writes to this part...
2
by: Cyril | last post by:
Hello, I have a problem to marshal a structure that contains an array of an others struct. This array is an array size fixed (MyStruct myStructs and not MyStruct *myStructs). For example : ...
6
by: Glenn | last post by:
OK, need help in translating what I'd like to do in old school C to best method C# If I was wanting to create an array of struct's, writing and reading them to/from a file.. how would I do this...
0
by: zman77 | last post by:
Hi. In C dll, there is a struct that contains an array of struct pointers. I do not know how to represent that in C#. That's my problem. Here is the relevant C code: struct vector { uint...
2
by: berrylthird | last post by:
This question was inspired by scripting languages such as JavaScript. In JavaScript, I can access members of a class using array syntax as in the following example: var myInstance:myClass = new...
1
by: Polaris | last post by:
Hi Experts: In my C# program I need to use a Win32 DLL which leads to a question: how to define Win32/C++ struct with array in C#. For example, I have a C++ struct: struct MY_STRUCT { int ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.