Re: Allocating structs on the stack
From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 07/27/04
- Next message: Jon Skeet [C# MVP]: "Re: putting string into MemoryStream"
- Previous message: Jon Skeet [C# MVP]: "Re: Why/How does Microsoft not follow the Interface contract"
- In reply to: CharleKann: "Allocating structs on the stack"
- Next in thread: CharleKann: "Re: Allocating structs on the stack"
- Reply: CharleKann: "Re: Allocating structs on the stack"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 27 Jul 2004 19:37:25 +0100
CharleKann <CharleKann@discussions.microsoft.com> wrote:
> I am preparing for a class this fall that teaches C# programming.
> Most of the students know Java, so I am trying to show some of the
> differences. One big academic issue to me is that use of structs in
> C#. I love that you can have stack allocation, and allocate them as
> part of an array.
Not at the same time, of course...
> However when trying to build a little application
> to show what is happening, I got some very strange and to me
> inconsistant behavior.
>
> Before being skewed in my class, I would like to know what is going
> on in this program. Apparently I cannot access properties in an
> instance of a struct until it is fully initialized (unless it is in
> an array, in which case the rule seems to not be implemented). This
> is a problem, as I wanted to make the fields private to hide them,
> and use the accessors. But I don't see to be able to.
>
> I can get around this by using the "new" operator, but once again, I
> wanted to avoid it to point out the difference between structs and
> classes.
Why should using the "new" operator be a problem? I would suggest that
using a constructor for a struct is the right way of creating an
instance.
> Anyway, the code I am working with is below. I commented out the line
> that causes the compiler to fail. Can anyone tell me what the
> justification is for it failing? And am I wrong, or are the rules
> different if it is an array?
The compiler doesn't know whether an array element has been fully
constructed, but it can check it for local variables.
-- Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too
- Next message: Jon Skeet [C# MVP]: "Re: putting string into MemoryStream"
- Previous message: Jon Skeet [C# MVP]: "Re: Why/How does Microsoft not follow the Interface contract"
- In reply to: CharleKann: "Allocating structs on the stack"
- Next in thread: CharleKann: "Re: Allocating structs on the stack"
- Reply: CharleKann: "Re: Allocating structs on the stack"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|