469,927 Members | 1,747 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,927 developers. It's quick & easy.

Value type intialization...

Hi!

The C# does not allow me to access
the value type variable before it is initialized:

MyStruct a;
a.Size(10);

Is there a way around that or is there a special
line where the constructors are called really
necessary

Thanks!
Atmapuri
Aug 31 '06 #1
3 1258
Nope; it must be assigned; what you have is comparable to:

int a;
a.ToString();

which fails for the same reason; you /must/ give it a starting value, even
if it is just "new MyStruct();"

Marc
Aug 31 '06 #2
As Marc correctly explained this is not possible. If you don't want to
create constructors I'd suggest using one standard that can be found in
almost all framework value types that is ro have a property Empty that
returns initialzied *empty* object. You can create and store such an object
in a static variable so you don't have to create a new one each time. Having
such a property you can write a code like the following:

Foo f = Foo.Empty;

Then you need to give value only to the field you use.
--
HTH
Stoitcho Goutsev (100)

"Marc Gravell" <ma**********@gmail.comwrote in message
news:uM**************@TK2MSFTNGP05.phx.gbl...
Nope; it must be assigned; what you have is comparable to:

int a;
a.ToString();

which fails for the same reason; you /must/ give it a starting value, even
if it is just "new MyStruct();"

Marc

Aug 31 '06 #3
Hi!

Thanks guys :)
Atmapuri

"Stoitcho Goutsev (100)" <10*@100.comwrote in message
news:Ob**************@TK2MSFTNGP06.phx.gbl...
As Marc correctly explained this is not possible. If you don't want to
create constructors I'd suggest using one standard that can be found in
almost all framework value types that is ro have a property Empty that
returns initialzied *empty* object. You can create and store such an
object in a static variable so you don't have to create a new one each
time. Having such a property you can write a code like the following:

Foo f = Foo.Empty;

Then you need to give value only to the field you use.
--
HTH
Stoitcho Goutsev (100)

"Marc Gravell" <ma**********@gmail.comwrote in message
news:uM**************@TK2MSFTNGP05.phx.gbl...
>Nope; it must be assigned; what you have is comparable to:

int a;
a.ToString();

which fails for the same reason; you /must/ give it a starting value,
even if it is just "new MyStruct();"

Marc


Sep 2 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

13 posts views Thread by Stumped and Confused | last post: by
10 posts views Thread by utab | last post: by
3 posts views Thread by =?Utf-8?B?Umljb2hEZXZlbG9wZXI=?= | last post: by
4 posts views Thread by ballygowanboy | last post: by
8 posts views Thread by Ralf Goertz | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.