Re: Why can't value types have initializers?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



On Mar 31, 4:42 am, "Patrice" <http://www.chez.com/scribe/> wrote:
And for instance initializers, it looks like this is for interop
compatiblity :

http://bytes.com/groups/net-c/228739-about-struct-csharp

That's not what the link says. It says that structs cannot have
initializers because they cannot have "default constructors", and they
cannot have those because then the runtime would have to execute them
whenever a struct is allocated. Which is something that CLR,
apparently, doesn't do. To put it simply, right now, when you write
"new Point[100]", you get 100 zero-filled points because the runtime
simply allocates a block of memory large enough, and zero-initializes
it (actually, probably the OS does the latter, not even CLR). But if
Point could have a default constructor, then the runtime would have to
execute that constructor for all 100 Point objects in the new array,
similar to how this happens in C++.

Now, this is certainly not impossible to do; but C# isn't C++ for a
reason. C++ rules for when constructors and destructors run can get
rather complicated at times (consider interaction with function
arguments, class members, exceptions etc).
.



Relevant Pages

  • Re: Using Structure vs Class for Datasource
    ... > The functionality I had in mind was inheritance, ... Well, structs *sort* of have inheritance too, in that you can use the ... operators, instance constructors, destructors and static constructors), ...
    (microsoft.public.dotnet.framework.performance)
  • SV: SV: Creating structs
    ... the compiler. ... "Structs cannot contain explicit parameterless constructors" ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: C/C++ typedef in C#
    ... sourcecode to an Angband variant and converting to c# to both practice ... typedef declarations(a small one for an example.) ... Here's the differences between structs and classes in C#:http://www.jaggersoft.com/pubs/StructsVsClasses.htm ... You may find it convenient to put some constructors in there, ...
    (rec.games.roguelike.development)
  • using malloc on a struct that has a CList
    ... There is a pretty messy linked list of structs in this tool. ... The structs are allocated with malloc(). ... so it would appear that the malloc does not allocate the correct space for a ... These structs do not have constructors. ...
    (microsoft.public.vc.mfc)
  • Re: using malloc on a struct that has a CList
    ... > There is a pretty messy linked list of structs in this tool. ... > The structs are allocated with malloc(). ... > so it would appear that the malloc does not allocate the correct space for ... These structs do not have constructors. ...
    (microsoft.public.vc.mfc)