class constructors in a struct

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pent

    #1

    class constructors in a struct

    Hi All,

    Why is this code valid? How can the static ctor be used? It doesn't act as
    class ctor at all.

    struct A
    {
    static A() { }
    }


  • 100

    #2
    Re: class constructors in a struct

    Hi Pent,
    "Pent" <pent> wrote in message
    news:%23ZsSEset DHA.2492@TK2MSF TNGP12.phx.gbl. ..[color=blue]
    > Why is this code valid?[/color]

    Yes, it is valid.
    [color=blue]
    > How can the static ctor be used?[/color]

    Static constructors is normally used to initialize static fields for a type.
    It is quaranteed to be called before any static filed is accessed. Don't
    realy on that the static constructor will be executed when the program
    starts, type is instantiaded or a static method is called. The only sure
    thing, how I said, is that the static constructor will be executed before a
    static filed is accessed.
    [color=blue]
    > It doesn't act as class ctor at all.[/color]

    Depends on what you mean by *class constructor*. CLR and IL Assembler call
    *.cctor* (class constructor) the same thing that C# calls *static
    constructor*. In this case it works how I already explained.
    If for you *class ctor* means instance constructor defined for a class
    (reference type) rather than for a struct (value type) then no, it doesn't.[color=blue]
    >
    > struct A
    > {
    > static A() { }
    > }
    >
    >[/color]
    If your problem is that you cannot declare parameterless constructor for
    structures that's right - you cannot. This is because if you instatiate
    value type without using *new* operator CLR doesn't call any constructor and
    this may leave your object uninitialized. So C# designers decided not to
    allow parameterless constructors for value types. This is good decision as
    long as CLR works this way.

    HTH
    B\rgds
    100


    Comment

    • Pent

      #3
      Re: class constructors in a struct

      The question is: What's the purpose of the following code:

      struct A
      {
      static A() { } //this is not called by CLR.
      }

      If there is no purpose for the above code, then why is it valid?

      "100" <100@100.com> wrote in message
      news:eG1VK$etDH A.2448@TK2MSFTN GP09.phx.gbl...[color=blue]
      > Hi Pent,
      > "Pent" <pent> wrote in message
      > news:%23ZsSEset DHA.2492@TK2MSF TNGP12.phx.gbl. ..[color=green]
      > > Why is this code valid?[/color]
      >
      > Yes, it is valid.
      >[color=green]
      > > How can the static ctor be used?[/color]
      >
      > Static constructors is normally used to initialize static fields for a[/color]
      type.[color=blue]
      > It is quaranteed to be called before any static filed is accessed. Don't
      > realy on that the static constructor will be executed when the program
      > starts, type is instantiaded or a static method is called. The only sure
      > thing, how I said, is that the static constructor will be executed before[/color]
      a[color=blue]
      > static filed is accessed.
      >[color=green]
      > > It doesn't act as class ctor at all.[/color]
      >
      > Depends on what you mean by *class constructor*. CLR and IL Assembler call
      > *.cctor* (class constructor) the same thing that C# calls *static
      > constructor*. In this case it works how I already explained.
      > If for you *class ctor* means instance constructor defined for a class
      > (reference type) rather than for a struct (value type) then no, it[/color]
      doesn't.[color=blue][color=green]
      > >
      > > struct A
      > > {
      > > static A() { }
      > > }
      > >
      > >[/color]
      > If your problem is that you cannot declare parameterless constructor for
      > structures that's right - you cannot. This is because if you instatiate
      > value type without using *new* operator CLR doesn't call any constructor[/color]
      and[color=blue]
      > this may leave your object uninitialized. So C# designers decided not to
      > allow parameterless constructors for value types. This is good decision[/color]
      as[color=blue]
      > long as CLR works this way.
      >
      > HTH
      > B\rgds
      > 100
      >
      >[/color]


      Comment

      • 100

        #4
        Re: class constructors in a struct

        Pent,

        Do you want the compiler to generate an error for each method with empty
        body you may have?
        Yes, your static constructor is redundant in this case, but it is not an
        error neither can lead to errors (as parameterless-instance constructors for
        value types). So why should be reported as so.

        BTW excution can be slightly different if you have

        struct Foo
        {
        static Bar bar = new Bar();
        ....... More static methods and fields
        }

        and

        struct Foo
        {
        static Bar bar = new Bar();
        ...... More static methods and fields
        static Foo(){}
        }

        Existence of redundant looking construtor in the second declaration may have
        impact on the moment when bar field will be created (Bar's constructor will
        be called).

        B\rgds
        100

        "Pent" <pent> wrote in message news:e8AFgPftDH A.1680@TK2MSFTN GP12.phx.gbl...[color=blue]
        > The question is: What's the purpose of the following code:
        >
        > struct A
        > {
        > static A() { } //this is not called by CLR.
        > }
        >
        > If there is no purpose for the above code, then why is it valid?
        >
        > "100" <100@100.com> wrote in message
        > news:eG1VK$etDH A.2448@TK2MSFTN GP09.phx.gbl...[color=green]
        > > Hi Pent,
        > > "Pent" <pent> wrote in message
        > > news:%23ZsSEset DHA.2492@TK2MSF TNGP12.phx.gbl. ..[color=darkred]
        > > > Why is this code valid?[/color]
        > >
        > > Yes, it is valid.
        > >[color=darkred]
        > > > How can the static ctor be used?[/color]
        > >
        > > Static constructors is normally used to initialize static fields for a[/color]
        > type.[color=green]
        > > It is quaranteed to be called before any static filed is accessed.[/color][/color]
        Don't[color=blue][color=green]
        > > realy on that the static constructor will be executed when the program
        > > starts, type is instantiaded or a static method is called. The only sure
        > > thing, how I said, is that the static constructor will be executed[/color][/color]
        before[color=blue]
        > a[color=green]
        > > static filed is accessed.
        > >[color=darkred]
        > > > It doesn't act as class ctor at all.[/color]
        > >
        > > Depends on what you mean by *class constructor*. CLR and IL Assembler[/color][/color]
        call[color=blue][color=green]
        > > *.cctor* (class constructor) the same thing that C# calls *static
        > > constructor*. In this case it works how I already explained.
        > > If for you *class ctor* means instance constructor defined for a class
        > > (reference type) rather than for a struct (value type) then no, it[/color]
        > doesn't.[color=green][color=darkred]
        > > >
        > > > struct A
        > > > {
        > > > static A() { }
        > > > }
        > > >
        > > >[/color]
        > > If your problem is that you cannot declare parameterless constructor for
        > > structures that's right - you cannot. This is because if you instatiate
        > > value type without using *new* operator CLR doesn't call any constructor[/color]
        > and[color=green]
        > > this may leave your object uninitialized. So C# designers decided not to
        > > allow parameterless constructors for value types. This is good decision[/color]
        > as[color=green]
        > > long as CLR works this way.
        > >
        > > HTH
        > > B\rgds
        > > 100
        > >
        > >[/color]
        >
        >[/color]


        Comment

        • Jon Skeet [C# MVP]

          #5
          Re: class constructors in a struct

          100 <100@100.com> wrote:[color=blue][color=green]
          > > How can the static ctor be used?[/color]
          >
          > Static constructors is normally used to initialize static fields for a type.
          > It is quaranteed to be called before any static filed is accessed. Don't
          > realy on that the static constructor will be executed when the program
          > starts, type is instantiaded or a static method is called. The only sure
          > thing, how I said, is that the static constructor will be executed before a
          > static filed is accessed.[/color]

          That's only true for types with the .beforefieldini t flag. For other
          types, there are more rigid rules.
          [color=blue][color=green]
          > > It doesn't act as class ctor at all.[/color]
          >
          > Depends on what you mean by *class constructor*. CLR and IL Assembler call
          > *.cctor* (class constructor) the same thing that C# calls *static
          > constructor*.[/color]

          Not quite. It's more usually known as a "type initializer" in the ECMA
          spec, although "class constructor" comes up as well - I'm not sure why
          they have both versions.

          In C#, you end up with a type initializer whenever you have static
          fields which have initial values. Unless you have a static constructor
          as well, the type is flagged as .beforefieldini t, which means that you
          only get the guarantee that the type initializer will be called some
          time before the fields get used for the first time. If you have a
          static constructor as well, you get more rigidly defined behaviour -
          the type initializer is only called when it absolutely has to be, but
          before the first call to a static method, access of a static field, or
          object construction.

          See http://www.pobox.com/~skeet/csharp/beforefieldinit.html for more
          explanation.

          --
          Jon Skeet - <skeet@pobox.co m>
          Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

          If replying to the group, please do not mail me too

          Comment

          • 100

            #6
            Re: class constructors in a struct

            Hi Jon,[color=blue]
            > 100 <100@100.com> wrote:[color=green][color=darkred]
            > > > How can the static ctor be used?[/color]
            > >
            > > Static constructors is normally used to initialize static fields for a[/color][/color]
            type.[color=blue][color=green]
            > > It is quaranteed to be called before any static filed is accessed.[/color][/color]
            Don't[color=blue][color=green]
            > > realy on that the static constructor will be executed when the program
            > > starts, type is instantiaded or a static method is called. The only sure
            > > thing, how I said, is that the static constructor will be executed[/color][/color]
            before a[color=blue][color=green]
            > > static filed is accessed.[/color]
            >
            > That's only true for types with the .beforefieldini t flag. For other
            > types, there are more rigid rules.[/color]

            Yes, I know that. We had this discussion before, but as long as the question
            wasn't "when the static constructor is called" I decided not to go into
            details. I said "the only sure thing... " because this is the point where we
            can say for sure that the static constructor has been called regardles of
            whether ".beforefieldin it" has been set or not.[color=blue]
            >[color=green][color=darkred]
            > > > It doesn't act as class ctor at all.[/color]
            > >
            > > Depends on what you mean by *class constructor*. CLR and IL Assembler[/color][/color]
            call[color=blue][color=green]
            > > *.cctor* (class constructor) the same thing that C# calls *static
            > > constructor*.[/color]
            >
            > Not quite. It's more usually known as a "type initializer" in the ECMA
            > spec, although "class constructor" comes up as well - I'm not sure why
            > they have both versions.[/color]

            *.cctor* stands for *class constructor* and I was guessing that this might
            be the source of confusion.
            Even though ECMA refers to that special method as *type initializer* CLR and
            ILAsm uses *.cctor* as a name. Furthermore (how you mentioned) ECMA uses
            *class constructor* as well; so, I don't thing that the actual name of this
            special method is so important as long as it doesn't lead to
            misunderstandin gs.

            [color=blue]
            > In C#, you end up with a type initializer whenever you have static
            > fields which have initial values. Unless you have a static constructor
            > as well, the type is flagged as .beforefieldini t, which means that you
            > only get the guarantee that the type initializer will be called some
            > time before the fields get used for the first time. If you have a
            > static constructor as well, you get more rigidly defined behaviour -
            > the type initializer is only called when it absolutely has to be, but
            > before the first call to a static method, access of a static field, or
            > object construction.[/color]

            Actually, if *beforefieldini t* is not specified, calling the type
            initializer is triggered by the first call to any static, instance or
            virtual method or access any static or instance field. Which means when one
            starts using the type.

            However C# specs doesn't mention beforefieldinit anywhere; I was palying
            arround and I couldn't get c# setting beforefieldinit for the type
            initilizer of my test class. Either ILDasm doesn't show that flag or my c#
            compiler doesn't use it. The tests, I performed, make me think that my c#
            comppiler never sets the flag.
            B\rgds
            100
            [color=blue]
            >
            > See http://www.pobox.com/~skeet/csharp/beforefieldinit.html for more
            > explanation.
            >
            > --
            > Jon Skeet - <skeet@pobox.co m>
            > http://www.pobox.com/~skeet
            > If replying to the group, please do not mail me too[/color]


            Comment

            • Jon Skeet [C# MVP]

              #7
              Re: class constructors in a struct

              100 <100@100.com> wrote:[color=blue][color=green]
              > > In C#, you end up with a type initializer whenever you have static
              > > fields which have initial values. Unless you have a static constructor
              > > as well, the type is flagged as .beforefieldini t, which means that you
              > > only get the guarantee that the type initializer will be called some
              > > time before the fields get used for the first time. If you have a
              > > static constructor as well, you get more rigidly defined behaviour -
              > > the type initializer is only called when it absolutely has to be, but
              > > before the first call to a static method, access of a static field, or
              > > object construction.[/color]
              >
              > Actually, if *beforefieldini t* is not specified, calling the type
              > initializer is triggered by the first call to any static, instance or
              > virtual method or access any static or instance field. Which means when one
              > starts using the type.[/color]

              The only way to call a virtual method or use an instance field is to
              create an instance though, surely... once an object which is an
              instance of a type (even if the type is a base class of the most
              specific type of the instance, as it were). (Apologies if this doesn't
              make sense - I've only had 45 minutes of sleep in the last 30-odd
              hours.)
              [color=blue]
              > However C# specs doesn't mention beforefieldinit anywhere; I was palying
              > arround and I couldn't get c# setting beforefieldinit for the type
              > initilizer of my test class. Either ILDasm doesn't show that flag or my c#
              > compiler doesn't use it. The tests, I performed, make me think that my c#
              > comppiler never sets the flag.[/color]

              No - it *always* sets the flag if you don't include a static
              constructor (at least in VS.NET 2003).

              Try this:

              using System;

              class WithoutStaticCo nstructor
              {
              }

              class WithStaticConst ructor
              {
              static WithStaticConst ructor()
              {
              }
              }

              Compile with:

              csc /target:library Filename.cs

              Open the dll and just expand the two types - beside the red triangle
              WithStaticConst ructor will have
              ..class private auto ansi
              and WithoutStaticCo nstructor will have
              ..class private auto ansi beforefieldinit

              (It works with exes as well.)

              --
              Jon Skeet - <skeet@pobox.co m>
              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

              If replying to the group, please do not mail me too

              Comment

              • 100

                #8
                Re: class constructors in a struct


                "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                news:MPG.1a3585 09d94733db989b7 a@msnews.micros oft.com...[color=blue]
                > 100 <100@100.com> wrote:[color=green][color=darkred]
                > > > In C#, you end up with a type initializer whenever you have static
                > > > fields which have initial values. Unless you have a static constructor
                > > > as well, the type is flagged as .beforefieldini t, which means that you
                > > > only get the guarantee that the type initializer will be called some
                > > > time before the fields get used for the first time. If you have a
                > > > static constructor as well, you get more rigidly defined behaviour -
                > > > the type initializer is only called when it absolutely has to be, but
                > > > before the first call to a static method, access of a static field, or
                > > > object construction.[/color]
                > >
                > > Actually, if *beforefieldini t* is not specified, calling the type
                > > initializer is triggered by the first call to any static, instance or
                > > virtual method or access any static or instance field. Which means when[/color][/color]
                one[color=blue][color=green]
                > > starts using the type.[/color]
                >
                > The only way to call a virtual method or use an instance field is to
                > create an instance though, surely... once an object which is an
                > instance of a type (even if the type is a base class of the most
                > specific type of the instance, as it were). (Apologies if this doesn't
                > make sense - I've only had 45 minutes of sleep in the last 30-odd
                > hours.)[/color]
                Yep, What I said is what can be found in ECMA.
                "4. If not marked BeforeFieldInit then that type's initializer method is
                executed at (i.e., is triggered by):
                * first access to any static or instance field of that type, or
                * first invocation of any static, instance or virtual method of that type"

                Of course you are right for that an instace or virtual method can be called
                only if the object is created. When an isntance of a class is created the
                instance constructor is executed and it triggers the class static
                constructor, I believe. Structures, though, can be created without instance
                constructor to be executed. In this case static constructor is not called
                upon creation. But it will be called if an instace method is called.
                [color=blue]
                >[color=green]
                > > However C# specs doesn't mention beforefieldinit anywhere; I was palying
                > > arround and I couldn't get c# setting beforefieldinit for the type
                > > initilizer of my test class. Either ILDasm doesn't show that flag or my[/color][/color]
                c#[color=blue][color=green]
                > > compiler doesn't use it. The tests, I performed, make me think that my[/color][/color]
                c#[color=blue][color=green]
                > > comppiler never sets the flag.[/color]
                >
                > No - it *always* sets the flag if you don't include a static
                > constructor (at least in VS.NET 2003).[/color]

                Yes, you are right. I was so surprised of this my "discovery" so I was
                inspecting my test project in the release subfolder until I was compiling in
                debug version. ;)
                However, the compiler doesn't put the beforefileinit flag C# specs will
                still be satisfied.

                "If a static constructor (ยง17.11) exists in the class,
                execution of the static field initializers occurs immediately prior to
                executing that static constructor. Otherwise,
                the static field initializers are executed at an implementation-dependent
                time prior to the first use of a static field
                of that class."

                Without .beforefieldini t everything is ok as well.

                B\rgds
                100


                Comment

                • Jon Skeet [C# MVP]

                  #9
                  Re: class constructors in a struct

                  100 <100@100.com> wrote:[color=blue]
                  > Yep, What I said is what can be found in ECMA.
                  > "4. If not marked BeforeFieldInit then that type's initializer method is
                  > executed at (i.e., is triggered by):
                  > * first access to any static or instance field of that type, or
                  > * first invocation of any static, instance or virtual method of that type"
                  >
                  > Of course you are right for that an instace or virtual method can be called
                  > only if the object is created. When an isntance of a class is created the
                  > instance constructor is executed and it triggers the class static
                  > constructor, I believe. Structures, though, can be created without instance
                  > constructor to be executed. In this case static constructor is not called
                  > upon creation. But it will be called if an instace method is called.[/color]

                  Ah yes - good point.
                  [color=blue][color=green]
                  > > No - it *always* sets the flag if you don't include a static
                  > > constructor (at least in VS.NET 2003).[/color]
                  >
                  > Yes, you are right. I was so surprised of this my "discovery" so I was
                  > inspecting my test project in the release subfolder until I was compiling in
                  > debug version. ;)[/color]

                  :)
                  [color=blue]
                  > However, the compiler doesn't put the beforefileinit flag C# specs will
                  > still be satisfied.[/color]

                  Yup - but as it does, people get confused :( That included me when
                  someone was saying a singleton was being created before he expected it
                  to be. I only found out about beforefieldinit at that stage...

                  --
                  Jon Skeet - <skeet@pobox.co m>
                  Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                  If replying to the group, please do not mail me too

                  Comment

                  Working...