473,387 Members | 3,820 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.

cannot have instance field initializers in structs

Could anyone tell me what is the reason I can't initialize the members of a
struct like this:

public struct SomeStruct
{
public int uno = 1; // Error
public int dos = 2; // Error
public int tres = 3; // Error
}

I understand that I can initialize the members by providing a constructor or
directly setting them, I just don't see the harm on doing the above.
Thank you.
Nov 16 '05 #1
6 21610
>Could anyone tell me what is the reason I can't initialize the members of a
struct like this:


Because the compiler moves the initialization code to the constructor.
But it can't generate a default constructor for structs.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2
I blogged about this a while back:

http://www.dotnetconsult.co.uk/weblo...0-f5f2773b4a7c

(watch for line breaks)

I mention field initializers at the end of the section on default constructors

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk/weblog

Could anyone tell me what is the reason I can't initialize the members of a
struct like this:

public struct SomeStruct
{
public int uno = 1; // Error
public int dos = 2; // Error
public int tres = 3; // Error
}

I understand that I can initialize the members by providing a constructor or
directly setting them, I just don't see the harm on doing the above.
Thank you.

Nov 16 '05 #3
I read your article and it was very interesting *however*, it appears that
the main reason not to allow a default constructor on a struct is because
you can have code in the constructor that could delay the creation of the
struc.

The problem that I have with this is "So What?" let the constructor take a
year to initialize, who cares. If I wanted to, I could have a constructor in
a regular class that takes 3 years to run and nobody cares, why this sudden
urge not to allow this from happening on a struct?

My guess is that something must be going on in the runtime that would get
screwed up if they let this happen, perhaps all application using the
runtime will stop working, perhaps, the garage collector would stop cleaning
while this goes on, I have no idea but that is exactly what I would like to
find out, do you know what it is?

Thank you.



"Richard Blewett [DevelopMentor]" <ri******@NOSPAMdevelop.com> wrote in
message news:eM**************@TK2MSFTNGP09.phx.gbl...
I blogged about this a while back:

http://www.dotnetconsult.co.uk/weblo...0-f5f2773b4a7c

(watch for line breaks)

I mention field initializers at the end of the section on default
constructors

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk/weblog

Could anyone tell me what is the reason I can't initialize the members
of a
struct like this:

public struct SomeStruct
{
public int uno = 1; // Error
public int dos = 2; // Error
public int tres = 3; // Error
}

I understand that I can initialize the members by providing a constructor
or
directly setting them, I just don't see the harm on doing the above.
Thank you.

Nov 16 '05 #4
Because when you allocate an array of reference types all you get is an array of references and therefore the allocation is always a known thing. With value type arrays, the memory for the value type is allocated inline and therefore needds to be initialized. If you provide a default constructor (or field initializer) that those would have to run as a result. This creates a potential hidden cost in array allocation for value types. Also, you can obtain value types from unmanaged code which certainly won't have run your default constructor code.

Why don't you put your initialization in a non-default constructor?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

I read your article and it was very interesting *however*, it appears that
the main reason not to allow a default constructor on a struct is because
you can have code in the constructor that could delay the creation of the
struc.

The problem that I have with this is "So What?" let the constructor take a
year to initialize, who cares. If I wanted to, I could have a constructor in
a regular class that takes 3 years to run and nobody cares, why this sudden
urge not to allow this from happening on a struct?

My guess is that something must be going on in the runtime that would get
screwed up if they let this happen, perhaps all application using the
runtime will stop working, perhaps, the garage collector would stop cleaning
while this goes on, I have no idea but that is exactly what I would like to
find out, do you know what it is?

Nov 16 '05 #5
Hey Richard:

Thanks for the respond. First things first, I don't really have a need to
implement my own default constructor or to manually initialize field
variables, I am just curios to know why this is not possible. At the end of
the day, I have to accept what the compiler allows me to do and it really
makes no different if I know what's going on behind the scenes or not but I
can't help my self!! :)

I am still not quite sure why would the runtime have a problem with how long
it would take to allocate my struct. As far as I am concern, the runtime
should say "screw the programmer", if it takes an hour to initialize this
struct because the programmer made a ridiculous default stuct then... who
cares?

Sorry for not getting it! Maybe I should give up programming and become a
porn star!!!

"Richard Blewett [DevelopMentor]" <ri******@NOSPAMdevelop.com> wrote in
message news:OQ**************@TK2MSFTNGP11.phx.gbl...
Because when you allocate an array of reference types all you get is an
array of references and therefore the allocation is always a known thing.
With value type arrays, the memory for the value type is allocated inline
and therefore needds to be initialized. If you provide a default
constructor (or field initializer) that those would have to run as a
result. This creates a potential hidden cost in array allocation for value
types. Also, you can obtain value types from unmanaged code which
certainly won't have run your default constructor code.

Why don't you put your initialization in a non-default constructor?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

I read your article and it was very interesting *however*, it appears
that
the main reason not to allow a default constructor on a struct is because
you can have code in the constructor that could delay the creation of the
struc.

The problem that I have with this is "So What?" let the constructor take a
year to initialize, who cares. If I wanted to, I could have a constructor
in
a regular class that takes 3 years to run and nobody cares, why this
sudden
urge not to allow this from happening on a struct?

My guess is that something must be going on in the runtime that would get
screwed up if they let this happen, perhaps all application using the
runtime will stop working, perhaps, the garage collector would stop
cleaning
while this goes on, I have no idea but that is exactly what I would like
to
find out, do you know what it is?

Nov 16 '05 #6
You can create a default ctor for a value type using IL rather than C#. However, the point is that the newarr IL opcode does not call it. It does one thing and one thing only to the memory of the allocated array - zero it. This is to make sure that array allocation is always a know quantity. For ref types this is straightforward as we just get null references, for value types though this adds a restriction. If we provided a default constructor then the newarr opcode should call it, but all it does is allocate a memory block of the correct size and zero it. So they would have to encode a call to the types default constuctor in the newarr opcode for value types on the offchance that someone had provided a custom default constructor. This would be a completely unnecessary overhead in the vast majority of situations, apart from the fact that value type arrays would then have to have special handling in JIT compilers handling of the newarr opcode.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Hey Richard:

Thanks for the respond. First things first, I don't really have a need to
implement my own default constructor or to manually initialize field
variables, I am just curios to know why this is not possible. At the end of
the day, I have to accept what the compiler allows me to do and it really
makes no different if I know what's going on behind the scenes or not but I
can't help my self!! :)

I am still not quite sure why would the runtime have a problem with how long
it would take to allocate my struct. As far as I am concern, the runtime
should say "screw the programmer", if it takes an hour to initialize this
struct because the programmer made a ridiculous default stuct then... who
cares?

Sorry for not getting it! Maybe I should give up programming and become a
porn star!!!

Nov 16 '05 #7

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

Similar topics

2
by: Paul Eaton | last post by:
Hi I am using asp/vbscript/ado/mssql. I am able to get the nullable property OK when generating a recordset with a simple SQL statement such as "select Fld1,Fld2 from Table1" and then looping...
19
by: Jasper Kent | last post by:
Can anyone explain the logic behind structs being allowed neither memeber initialisers or default constructors. Doesn't this just encourage developers to create constructors with dummy...
0
by: weixian_shen | last post by:
I'm trying to call my DLL written in C, and got the error: Cannot marshal field 'b' of type 'mystruct': There is no marshaling support for this type. The 2 functions in the DLL are: void...
1
by: Jeff Schiller | last post by:
I have Visual Studio 7.1 and I wrote the following C++ program #include <iostream using namespace std class ID private static unsigned long s_id public static unsigned long Next(
8
by: Dave A | last post by:
I have a class called 'PrimaryKey' that represents the primary key of a table. PrimaryKeys can only be created and the class only implements .ToString(). The PrimaryKey class internally stores...
2
by: cody | last post by:
class Test { IList list = new ArrayList(); MyCollection list2 = new MyCollection (list); } Leads to this error. I know I could initialize them in the ctor but I'm asking myself where this...
1
by: r035198x | last post by:
Inspiration Inspired by a post by Jos in the Java forum, I have put together a little article on class initializers. Initializers are indeed underutilized by most Java programmers. Once the Java...
2
by: bhughes2187 | last post by:
Ok, here is the scoop. I have a report that I am designing. Now, the table that the data comes from, has an field called ATTRIBUTE. This field is populated with an R to indicate when a page break...
2
by: Ifeanyi Okoye | last post by:
I have 6 tables in MS Access 2010, each with varying number of fields and I have specified a relationship between the tables. I started designing a single paged form to hold all the fields in my...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: 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...
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
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...
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.