473,387 Members | 1,897 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,387 software developers and data experts.

one line struct initialization

Is it possible, as in C? I don't think it is. Just checking.

Zytan

Mar 7 '07 #1
21 10512
>Is it possible, as in C? I don't think it is. Just checking.
If you provide a constructor that will initialize all members.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 7 '07 #2
On 6 Mar 2007 20:03:39 -0800, "Zytan" <zy**********@yahoo.comwrote:
>Is it possible, as in C? I don't think it is. Just checking.
Why wouldn't it be possible? What exactly are you referring to?
--
http://www.kynosarges.de
Mar 7 '07 #3
Is it possible, as in C? I don't think it is. Just checking.
>
Why wouldn't it be possible? What exactly are you referring to?
I mean like so:

int x = 4; // declared and initialized in one line

struct abc { ... };
abc = ...; // declared and initialized in one line. Is this possible?

Zytan

Mar 7 '07 #4
Is it possible, as in C? I don't think it is. Just checking.
>
If you provide a constructor that will initialize all members.
I wasn't looking to use a constructor. But, maybe I need one.
Does "int x = 4;" invoke a constructor for 'int'? Is that how
declarations and initializations are done on the same line?

Zytan

Mar 7 '07 #5
struct abc { ... };
abc = ...; // declared and initialized in one line. Is this possible?
Oops, I mean:

struct abc { ... };
abc y = ...; // declared and initialized in one line. Is this
possible?

Zytan

Mar 7 '07 #6
>I wasn't looking to use a constructor. But, maybe I need one.
Well maybe you can get by with an implicit conversion operator
instead. It depends on what kind of expression you want on the right
hand side of the assignment.

One way or another the RHS expression must be turned into an instance
of your struct.

>Does "int x = 4;" invoke a constructor for 'int'?
No, but int in special since you can write literals for it in C# and
there are special IL opcodes for it.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 7 '07 #7
Zytan <zy**********@yahoo.comwrote:
>Is it possible, as in C? I don't think it is. Just checking.
If you provide a constructor that will initialize all members.

I wasn't looking to use a constructor. But, maybe I need one.
Does "int x = 4;" invoke a constructor for 'int'? Is that how
declarations and initializations are done on the same line?
Well, the primitive types are a special case - but yes, if you want to
initialize a struct, you generally need to call a constructor. 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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 7 '07 #8
Well maybe you can get by with an implicit conversion operator
instead. It depends on what kind of expression you want on the right
hand side of the assignment.

One way or another the RHS expression must be turned into an instance
of your struct.
Yes, it sounds like using a constructor is the proper way, then.
Does "int x = 4;" invoke a constructor for 'int'?

No, but int in special since you can write literals for it in C# and
there are special IL opcodes for it.
Right, that's what I thought.

Zytan

Mar 7 '07 #9
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 };
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.

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)?

Zytan

Mar 7 '07 #10
"Zytan" <zy**********@yahoo.comwrote in message
news:11*********************@n33g2000cwc.googlegro ups.com...
struct abc { ... };
abc y = ...; // declared and initialized in one line. Is this
possible?
What goes in the dots.

///ark
Mar 7 '07 #11
What goes in the dots.

struct abc { int x; double y; AnotherStruct s; };
abc y = { 100, 3.14, ??? };

It works up until the ???, since it's a struct. I don't know what to
put there.

Zytan

Mar 7 '07 #12
Zytan <zy**********@yahoo.comwrote:
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 - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 7 '07 #13
Zytan <zy**********@yahoo.comwrote:
What goes in the dots.

struct abc { int x; double y; AnotherStruct s; };
abc y = { 100, 3.14, ??? };

It works up until the ???, since it's a struct. I don't know what to
put there.
You don't do it like that - you have a constructor, and do:

abc y = new abc (100, 3.14, new AnotherStruct(...));

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 7 '07 #14
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) };
Yes, sorry, I didn't mean that I wanted an array of struct, I mean
that I wanted to do something like this:

MySrtuct x = new MyStruct { field1, field2, field3, field4 };

Where fieldX are the fields in MyStruct, which could, themselves, be
structs.
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.
Even for structs? But sometimes a struct is just something simple,
like holding x and y for the concept of a point.
If you
need to access them from outside, use methods or properties.
Ok, I will try adding a constructor, and making everyting private. I
think in my case this will do just fine.
A mutable
struct would be one which let you change the values, whether via
properties or methods (or, of course, non-private fields).
Ok.

Zytan

Mar 8 '07 #15
struct abc { int x; double y; AnotherStruct s; };
abc y = { 100, 3.14, ??? };
It works up until the ???, since it's a struct. I don't know what to
put there.

You don't do it like that - you have a constructor, and do:

abc y = new abc (100, 3.14, new AnotherStruct(...));
Ok. Thanks, Jon.

Zytan

Mar 8 '07 #16
On Mar 7, 5:50 pm, "Zytan" <zytanlith...@yahoo.comwrote:
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) };

Yes, sorry, I didn't mean that I wanted an array of struct, I mean
that I wanted to do something like this:

MySrtuct x = new MyStruct { field1, field2, field3, field4 };

Where fieldX are the fields in MyStruct, which could, themselves, be
structs.
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.

Even for structs? But sometimes a struct is just something simple,
like holding x and y for the concept of a point.
Yes, but be careful here: note the difference between making a point a
class versus making it a struct.

If you make a Point class, then you hold references to instances, and
usually (unless you Clone) you can have many references pointing to
the same instance. Change the instance and the data accessible through
all of the relevant references changes. (That is, conceptually, if you
change the coordinates of the point instance then many parts of your
program may see that change.) As well, a Point class instance is
"defined" by more than just its coordinates: you can have only one
instance of (5, 4), or two instance, or a dozen, and it makes sense to
talk about "this instance of (5, 4) versus that one."

If you make a Point struct, then you simply hold the value (5, 4).
Whenever you pass it or assign it to another Point, you create a copy.
It is a value, like an integer, and so changing one value does not
affect any other value with the same coordinates. A Point struct is
defined only by its coordinates and nothing else: one (5, 4) is
equivalent to any other (5, 4). It makes no sense to talk about "this
(5, 4) versus that one."

I don't know how good an explanation that was, but the point (if
you'll pardon the pun) is that the semantics change significantly.

The reason that you usually want immutable structs (that is, structs
with constructors that initialize all members, no public fields, and
no properties with setters or methods that change the struct's value)
is that struct is usually intended to create new value types, like
double, int, float, DateTime, etc. Most ex-C programmers (like me) try
at least once to use "struct" to build a "light" class of just fields
and no methods. I tried to use it for StockItem or some such thing. It
was a disastrously bad idea. I learned my lesson.

I now have a Fraction struct that allows me to perform math on
fractions. The struct has properties and methods, but note that any
property or method that would usually alter the struct instead returns
a new one. For example:

public Fraction Normalize()
{
Fraction result = ... ;
return result;
}

So instead of normalizing a Fraction by saying fract.Normalize(), I
have to say:

Fraction norm = fract.Normalize();

Again, it's a value, not a class instance. Values generally don't
morph themselves into other values: variables are rather assigned new
values. (If you want a parallel with native types, you aren't allowed
to mess with the individual bits in an integer, but you are allowed to
do an operation that masks out bits in an integer and then assign the
result back to the same variable that held the original integer.)

Mar 8 '07 #17
Zytan <zy**********@yahoo.comwrote:
MyStruct[] x = new MyStruct[] { new MyStruct(1), new MyStruct(2) };

Yes, sorry, I didn't mean that I wanted an array of struct, I mean
that I wanted to do something like this:

MySrtuct x = new MyStruct { field1, field2, field3, field4 };

Where fieldX are the fields in MyStruct, which could, themselves, be
structs.
Well, change the braces to brackets and define the appropriate
constructor, and you're there.
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.

Even for structs? But sometimes a struct is just something simple,
like holding x and y for the concept of a point.
That doesn't mean it's not worth encapsulating them in properties.
Non-private fields are highly discouraged. You get much more control
and power with properties. You can add in validation etc later, or even
potentially change the underlying type/implementation without callers
caring.
If you
need to access them from outside, use methods or properties.

Ok, I will try adding a constructor, and making everyting private. I
think in my case this will do just fine.
Goodo.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 8 '07 #18
Bruce, wow, that was an amazing explanation! Thanks!
Even for structs? But sometimes a struct is just something simple,
like holding x and y for the concept of a point.

Yes, but be careful here: note the difference between making a point a
class versus making it a struct.
[snip]
Yes, I already knew the fine differences between references and value
types. I think of references as pointers to data, and by making more
pointers to the same data, if you change the data, all of the usage of
any of those pointers to it will see the changed data. Your
explanation was perfect, however.
The reason that you usually want immutable structs (that is, structs
with constructors that initialize all members, no public fields, and
no properties with setters or methods that change the struct's value)
is that struct is usually intended to create new value types, like
double, int, float, DateTime, etc.
Ah, so now I get it. This is the key. If you use struct as a new
value type, then, yes, the data within it should never change. It is
set on construction. And if it should change, it would be as the
result of an overloaded assignment operator. I totally get it now.
Thanks.
Most ex-C programmers (like me) try
at least once to use "struct" to build a "light" class of just fields
and no methods. I tried to use it for StockItem or some such thing. It
was a disastrously bad idea. I learned my lesson.
Well, right now, I want to use a struct to basically store a bunch of
data (strings, ints, etc.) that are all related. I really have no use
to doing anything 'on' them, such as add them together, or whatever,
or even change them. I just want to store the information into one
variable, and later look at it. So, I could make the fields all
private, and then make readonly properties for each, but it's so much
easier to just make them public (but, yes, that means you could change
them, so it's quicker code, but not as robust).

I totally agree with you for such cases as when you want to make a new
value type -- now I get why to use a struct with methods. That's
basically what all the elementary values types are (well, in concept,
anwyay).

Bruce, thanks for this amazing explanation. It's so basic and
elementary, but it is so powerful at the same time.

Zytan

Mar 8 '07 #19
Yes, sorry, I didn't mean that I wanted an array of struct, I mean
that I wanted to do something like this:
MySrtuct x = new MyStruct { field1, field2, field3, field4 };
Where fieldX are the fields in MyStruct, which could, themselves, be
structs.

Well, change the braces to brackets and define the appropriate
constructor, and you're there.
Right.
Even for structs? But sometimes a struct is just something simple,
like holding x and y for the concept of a point.

That doesn't mean it's not worth encapsulating them in properties.
Non-private fields are highly discouraged. You get much more control
and power with properties. You can add in validation etc later, or even
potentially change the underlying type/implementation without callers
caring.
Yes, that's true. I will do this.

Thanks, Jon

Zytan

Mar 8 '07 #20
Even for structs? But sometimes a struct is just something simple,
like holding x and y for the concept of a point.
That doesn't mean it's not worth encapsulating them in properties.
Non-private fields are highly discouraged. You get much more control
and power with properties. You can add in validation etc later, or even
potentially change the underlying type/implementation without callers
caring.

Yes, that's true. I will do this.
Actually, the readonly modifier could be useful. It doesn't allow
validation or letting the underlying implementation change, but in my
case, there is nothing to validate, it's just a storage place for
strings/ints, to *later* to analyzed, such as for network traffic. I
don't want to validate it on storage, I'll do that later. This struct
is storing to make it easier to analyze later, rather than attempting
to analyze too much info at once. And, the underlying structure will
never change (if it ever does, a lot more than this struct would have
to change).

I assume it is ok for me to use readonly. Some people must use it
properly somewhere, or it wouldn't be included in the language.

Zytan

Mar 8 '07 #21
Zytan <zy**********@yahoo.comwrote:
Yes, that's true. I will do this.

Actually, the readonly modifier could be useful. It doesn't allow
validation or letting the underlying implementation change, but in my
case, there is nothing to validate, it's just a storage place for
strings/ints, to *later* to analyzed, such as for network traffic. I
don't want to validate it on storage, I'll do that later. This struct
is storing to make it easier to analyze later, rather than attempting
to analyze too much info at once. And, the underlying structure will
never change (if it ever does, a lot more than this struct would have
to change).

I assume it is ok for me to use readonly. Some people must use it
properly somewhere, or it wouldn't be included in the language.
There's nothing wrong with readonly - but it doesn't mean that it
wouldn't be better to provide properties than public variables.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 8 '07 #22

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

Similar topics

13
by: Jayw710 | last post by:
hi all, this should be basic, but I can't seem to get the right syntax. i have a struct struct PTStruct { int x; int y;
4
by: Greg B | last post by:
Well since getopt() doesn't seem to be compatible with Windows, and the free implementation of it for Windows that I found still had some annoying restrictions, I thought I'd whip up a simple...
3
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
10
by: emma middlebrook | last post by:
Hi I discovered that if you declare a structure (and not 'new()' it) you can then separately initialize its members and the compiler counts those separate statements as a full initialization....
3
by: Karl M | last post by:
Hi everyone, I just notice some strange behaviors on the MS C++ compiler regarding struct default constructor, see the example bellow: struct MyStruct { int a; }; class MyClass { public:
4
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or...
6
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a...
18
by: Ehud Shapira | last post by:
Is it possible to have a declaration of a struct pointer initialized to an unnamed struct? (I'm only concerned with static/global variables, if it matters.) I'm trying to do something like: ...
5
by: ssylee | last post by:
I'm not sure if I can initialize members of a struct the lazy way. For example, let's say I have a struct defined as below: typedef struct _ABC { BOOL A; BOOL B; BOOL C; } ABC;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.