Re: one line struct initialization
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Wed, 7 Mar 2007 21:17:41 -0000
Zytan <zytanlithium@xxxxxxxxx> wrote:
Well, the primitive types are a special case - but yes, if you want to
initialize a struct, you generally need to call a constructor.
I guess I was just looking for something as simple as what you can do
with initializing an array:
int[] x = new int[] { 4, 5, 6, 7 };
Well, you can do:
MyStruct[] x = new MyStruct[] { new MyStruct(1), new MyStruct(2) };
etc
If it's
a mutable struct (generally a bad idea) you *could* just do:
MyStruct x;
x.SomeProperty = ...;
but it's generally better to have a constructor which fully constructs
the struct, and call that.
Yes, I think I need a constructor. I did notice that C# complains if
you only initialize a portion of the fields in the struct (if you miss
one) and then attempt to use it. So, it is safe (perhaps not so in
earlier versions?). But, a c'tor seems more safe.
Yes, that's much better.
A mutable struct is a bad idea? What is a mutable struct? I know
mutable means it can change. But, unless all fields are private,
isn't the struct mutable? Or is this precisely what you mean, that
struct fields should all be private (almost like a class)?
All fields *should* be private, for both structs and classes. If you
need to access them from outside, use methods or properties. A mutable
struct would be one which let you change the values, whether via
properties or methods (or, of course, non-private fields).
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: one line struct initialization
- From: Zytan
- Re: one line struct initialization
- References:
- one line struct initialization
- From: Zytan
- Re: one line struct initialization
- From: Mattias Sjögren
- Re: one line struct initialization
- From: Zytan
- Re: one line struct initialization
- From: Jon Skeet [C# MVP]
- Re: one line struct initialization
- From: Zytan
- one line struct initialization
- Prev by Date: Array index
- Next by Date: Re: struct ToString() not automatically invoked
- Previous by thread: Re: one line struct initialization
- Next by thread: Re: one line struct initialization
- Index(es):
Relevant Pages
|