473,695 Members | 2,305 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

remove struct's default constructor?

I have a struct constructor to initialize all of my private (or public
readonly) fields. There still exists the default constructor that sets
them all to zero. Is there a way to remove the creation of this
implicit default constructor, to force the creation of a struct via my
constructor only?

Zytan

Mar 8 '07 #1
74 15989
On 8 Mar 2007 14:21:39 -0800, "Zytan" <zy**********@y ahoo.comwrote:
>I have a struct constructor to initialize all of my private (or public
readonly) fields. There still exists the default constructor that sets
them all to zero. Is there a way to remove the creation of this
implicit default constructor, to force the creation of a struct via my
constructor only?

Zytan
Declare your own default constructor private:

struct MyStruct {

public MyStruct(int data) {
// Do stuff
}

private MyStruct() { }
}

Because you have declared your own default constructor the compiler
will not create one. Because you have declared it private no-one
except you can ever call it. This makes your struct impossible to
default construct, which will limit its use in some situations.

rossum

Mar 8 '07 #2


"rossum" <ro******@coldm ail.comwrote in message
news:oc******** *************** *********@4ax.c om...
On 8 Mar 2007 14:21:39 -0800, "Zytan" <zy**********@y ahoo.comwrote:
>>I have a struct constructor to initialize all of my private (or public
readonly) fields. There still exists the default constructor that sets
them all to zero. Is there a way to remove the creation of this
implicit default constructor, to force the creation of a struct via my
constructor only?

Zytan
Declare your own default constructor private:

struct MyStruct {

public MyStruct(int data) {
// Do stuff
}

private MyStruct() { }
}
error CS0568: Structs cannot contain explicit parameterless constructors

David

Mar 8 '07 #3
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** **************@ 8g2000cwh.googl egroups.com...
>I have a struct constructor to initialize all of my private (or public
readonly) fields. There still exists the default constructor that sets
them all to zero. Is there a way to remove the creation of this
implicit default constructor, to force the creation of a struct via my
constructor only?

Zytan

Not sure what you mean here with default constructor, there is no such thing as a "default"
constructor for structs.
If you don't supply a constructor, the struct will get initialized by the runtime, such that
all its fields have their default value, that is, the memory space (f.i on the stack) taken
by the struct is set to 0. There is no way to suppress this "initializa tion ", which is a
good thing.

Willy.

Mar 8 '07 #4
Not sure what you mean here with default constructor, there is no such thing as a "default"
constructor for structs.
http://msdn2.microsoft.com/en-us/lib...ft(vs.80).aspx

"Each struct already has a default constructor that initializes the
object to zero. Therefore, the constructors that you can create for a
struct must take one or more parameters."
If you don't supply a constructor, the struct will get initialized by the runtime, such that
all its fields have their default value, that is, the memory space (f.i on the stack) taken
by the struct is set to 0.
Yes, by the default constructor.
There is no way to suppress this "initializa tion ", which is a
good thing.
No, it's bad. Because I have a struct that contains only private data
members, as Jon Skeet wondefully pointed out is a good thing to do.
Therefore, I can only initialize those private members via constructor
(or declaration assignment -- I am not sure of the terminology of
that). Thus, if the default constructor does not disappear once I
create my own struct constructor, the caller can create a struct still
using the default constructor, setting all private / readonly fields
to 0, and they can never be changed. This is unfortunate for any
struct that has manually created constructors / properties that so
validity checking on the parameters.

(Althouhgh, for structs that have NO manually created constructors, I
agree that the default constructor that sets all fields to 0 is a good
thing.)

Zytan

Mar 8 '07 #5
Declare your own default constructor private:
>
private MyStruct() { }
http://msdn2.microsoft.com/en-us/lib...ft(vs.80).aspx
"Compiler Error CS0568
Error Message
Structs cannot contain explicit parameterless constructors
Each struct already has a default constructor that initializes the
object to zero. Therefore, the constructors that you can create for a
struct must take one or more parameters."
Because you have declared your own default constructor the compiler
will not create one. Because you have declared it private no-one
except you can ever call it. This makes your struct impossible to
default construct, which will limit its use in some situations.
Yes, that thought works in C++ to prevent instantiation (to create
'static' classes that C++ does not support), and I thought maybe I
could do it in C#, as you've thought, as well, but it doesn't work.

Zytan

Mar 8 '07 #6
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** **************@ 64g2000cwx.goog legroups.com...
>Not sure what you mean here with default constructor, there is no such thing as a
"default"
constructor for structs.

http://msdn2.microsoft.com/en-us/lib...ft(vs.80).aspx
Ever heard of mistakes in MSDN?
"Each struct already has a default constructor that initializes the
object to zero. Therefore, the constructors that you can create for a
struct must take one or more parameters."
>If you don't supply a constructor, the struct will get initialized by the runtime, such
that
all its fields have their default value, that is, the memory space (f.i on the stack)
taken
by the struct is set to 0.

Yes, by the default constructor.
No there is no *explicit* .ctor created by the compiler for a value type as it's the case
for a class, take a look at the IL using ildasm.
>There is no way to suppress this "initializa tion ", which is a
good thing.

No, it's bad. Because I have a struct that contains only private data
members, as Jon Skeet wondefully pointed out is a good thing to do.
Therefore, I can only initialize those private members via constructor
(or declaration assignment -- I am not sure of the terminology of
that). Thus, if the default constructor does not disappear once I
create my own struct constructor, the caller can create a struct still
using the default constructor, setting all private / readonly fields
to 0, and they can never be changed. This is unfortunate for any
struct that has manually created constructors / properties that so
validity checking on the parameters.

(Althouhgh, for structs that have NO manually created constructors, I
agree that the default constructor that sets all fields to 0 is a good
thing.)

Zytan

Mar 9 '07 #7
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** **************@ 64g2000cwx.goog legroups.com...
>Not sure what you mean here with default constructor, there is no such thing as a
"default"
constructor for structs.

http://msdn2.microsoft.com/en-us/lib...ft(vs.80).aspx

"Each struct already has a default constructor that initializes the
object to zero. Therefore, the constructors that you can create for a
struct must take one or more parameters."
>If you don't supply a constructor, the struct will get initialized by the runtime, such
that
all its fields have their default value, that is, the memory space (f.i on the stack)
taken
by the struct is set to 0.

Yes, by the default constructor.
>There is no way to suppress this "initializa tion ", which is a
good thing.

No, it's bad. Because I have a struct that contains only private data
members, as Jon Skeet wondefully pointed out is a good thing to do.
Therefore, I can only initialize those private members via constructor
(or declaration assignment -- I am not sure of the terminology of
that). Thus, if the default constructor does not disappear once I
create my own struct constructor, the caller can create a struct still
using the default constructor, setting all private / readonly fields
to 0, and they can never be changed. This is unfortunate for any
struct that has manually created constructors / properties that so
validity checking on the parameters.
What else do you want? structs are stored on the stack (or inlined with a heap allocated
object instance), that means if the fields are not set to their default value, that they
will contain the trash that's still in the stack.

say you have:
struct S
{
int i;
SomeObject obj;
}

if S wouldn't be set to 0, SomeObject could contain an address, left on the stack from a
previous call frame possibly containing a valid pointer or even a valid object reference,
but not a reference of SomeObject type, use your imaginatio and think what could happen in
such case....

(Althouhgh, for structs that have NO manually created constructors, I
agree that the default constructor that sets all fields to 0 is a good
thing.)
No, its a perfect thin for all. If you don't want the struct to be initialized with default
values, make sure they are initialized correctly and handle the error cases.
Willy.

Mar 9 '07 #8
Not sure what you mean here with default constructor, there is no such thing as a
"default"
constructor for structs.
http://msdn2.microsoft.com/en-us/lib...ft(vs.80).aspx

Ever heard of mistakes in MSDN?
Yes. Why the attitude? It's ok to be called on something you believe
is right.

I believe MSDN is correct this time because of further evidence
explained below.
"Each struct already has a default constructor that initializes the
object to zero. Therefore, the constructors that you can create for a
struct must take one or more parameters."
If you don't supply a constructor, the struct will get initialized by the runtime, such
that
all its fields have their default value, that is, the memory space (f.i on the stack)
taken
by the struct is set to 0.
Yes, by the default constructor.

No there is no *explicit* .ctor created by the compiler for a value type as it's the case
for a class, take a look at the IL using ildasm.
Perhaps just because it is not explicitly created, it doesn't mean
that it's conceptually not there. Any basic value data type would be
foolish to have a constructor when all you need to do is shove zero(s)
into memory address(es).

So, you are saying there is no default constructor for structs, not
even conceptually? Then why does C# refuse the attempt to create a
struct constructor with no parameters? If there's no default
constructor, there should be no issue doing so. I think the reason
why is that one is implied, even thought it doesn't actually exist
explicitly in the byte code.

I think it is perhaps pedantic to state there is no constructor if
there really is one conceptually, but just not explicitly in the byte
code. But, I could be wrong. I don't know enough to know for sure.
I don't know what conceptual designs the byte code hides, if any.

Zytan

Mar 9 '07 #9
No, it's bad. Because I have a struct that contains only private data
members, as Jon Skeet wondefully pointed out is a good thing to do.
Therefore, I can only initialize those private members via constructor
(or declaration assignment -- I am not sure of the terminology of
that). Thus, if the default constructor does not disappear once I
create my own struct constructor, the caller can create a struct still
using the default constructor, setting all private / readonly fields
to 0, and they can never be changed. This is unfortunate for any
struct that has manually created constructors / properties that so
validity checking on the parameters.

What else do you want? structs are stored on the stack (or inlined with a heap allocated
object instance), that means if the fields are not set to their default value, that they
will contain the trash that's still in the stack.
Willy, you are missing my point.

Yes, junk would exist if no constructor is called. But, if I force
any use of a struct to use my constructor, then the values will be
what the constructor forces them to be. This is even better than
having them zeroed out. Imagine only having proper values. Zerod
values are better than junk values. Proper values are even better
than zeroed values.
if S wouldn't be set to 0, SomeObject could contain an address, left on the stack from a
previous call frame possibly containing a valid pointer or even a valid object reference,
but not a reference of SomeObject type, use your imaginatio and think what could happen in
such case....
I know all about it, Willy. I think it's great that languages
determine when variables are used before they are initialized, and C++
(at run time) and C# (at compile time, even better) are two such
languages. The above scenario, should never occur, even if variables
are not zeroed out. But, yes, zeroing them out adds an extra layer of
protection, I agree.
(Although, for structs that have NO manually created constructors, I
agree that the default constructor that sets all fields to 0 is a good
thing.)

No, its a perfect thing for all.
No, it's not perfect for all. How can you claim that? For my struct,
it should never, ever have zeros in it. Ever. Zeros are just not
proper values. Either the struct doesn't exist, or it exists with
specific values passed into its constructor. There is never a time
that it ever makes sense to have zeroes in it. Thus, if I can force
my constructor to be invoked every single time the struct is used,
then in all cases in the program, the struct will only ever contain
real, proper values, and will never contain imporper zero values.

To make such a claim "something is perfect for all" implies you've
thought of infinite possible cases. It's an impossible claim to make,
and can be disproven with a single case. I thought I had explained
that case prior to this post. I hope the above explains it
adequately.

I am dumbfounded as to your defensive behaviour. Did it arrive from
my claim that you were wrong that structs don't have a constructor?
All I am trying to do is find the truth by discussion. If I'm wrong,
I don't care, as long as I find the truth. My being wrong on one
thing doesn't make me automatically wrong on another.
If you don't want the struct to be initialized with default
values, make sure they are initialized correctly and handle the error cases.
But that means I must manually do what the compiler could handle for
me. I think the arrival of strict type checking showed why it is best
that the compiler handle as much as it can, since humans are prone to
error.

Zytan

Mar 9 '07 #10

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

Similar topics

12
2114
by: Peter van der Goes | last post by:
When a struct is created in C# and a parameterized constructor defined, the IntelliSense editor shows only the syntax for the parameterized constructor in tooltips, but not for the default constructor which appears to still exist. If this is not designed behavior, is it a bug or am I misusing my struct? If it is by design, could you please explain? I realize the behavior of a struct, as regards constructors, is different from that of...
3
1908
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:
0
8631
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
8572
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
9115
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
8984
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6491
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5839
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
4340
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3003
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
2272
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.