Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Static constructor [SOLVED]

Static constructor [SOLVED]

Scheduled Pinned Locked Moved C#
csharphelptutorialquestionlearning
12 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M mabrahao

    I am learning C# and OOP, i just cant understand how a static constructor can be useful... can someone please help me with this?? if possible, can u give a simple example? thank you very much... Marcus Abrahão Thank you all very much for your help

    modified on Wednesday, January 6, 2010 7:12 AM

    S Offline
    S Offline
    Saksida Bojan
    wrote on last edited by
    #2

    mabrahao wrote:

    static constructor can be useful

    No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

    public class Test
    {
    // Constructor
    public Test(){}

    public static Color GetColor()
    {
    return Color.White;
    }
    }

    // somewher in your app

    Color c = Test.GetColor(); // Test t = New Test() was never called.

    OriginalGriffO M P D 4 Replies Last reply
    0
    • M mabrahao

      I am learning C# and OOP, i just cant understand how a static constructor can be useful... can someone please help me with this?? if possible, can u give a simple example? thank you very much... Marcus Abrahão Thank you all very much for your help

      modified on Wednesday, January 6, 2010 7:12 AM

      V Offline
      V Offline
      V 0
      wrote on last edited by
      #3

      Have a look on MSDN[^] Hope this helps.

      V.
      Stop smoking so you can: Enjoy longer the money you save. Moviereview Archive

      M 1 Reply Last reply
      0
      • S Saksida Bojan

        mabrahao wrote:

        static constructor can be useful

        No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

        public class Test
        {
        // Constructor
        public Test(){}

        public static Color GetColor()
        {
        return Color.White;
        }
        }

        // somewher in your app

        Color c = Test.GetColor(); // Test t = New Test() was never called.

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #4

        Saksida Bojan wrote:

        mabrahao wrote: static constructor can be useful No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

        This turns out not to be the case: Static Constructor[^]

        All those who believe in psycho kinesis, raise my hand.

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        S 1 Reply Last reply
        0
        • S Saksida Bojan

          mabrahao wrote:

          static constructor can be useful

          No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

          public class Test
          {
          // Constructor
          public Test(){}

          public static Color GetColor()
          {
          return Color.White;
          }
          }

          // somewher in your app

          Color c = Test.GetColor(); // Test t = New Test() was never called.

          M Offline
          M Offline
          mabrahao
          wrote on last edited by
          #5

          Ok, static methods and static class was able to figure out how it works, but not the STATIC CONSTRUCTOR, like so: public class Test { int numTest; // Static Constructor static Test() { numTest = 5; } } i am reading a book from Andrew Troelsen, about C#, and in the book, he gives a example of a static constructor, but i just could not understand... anyway, thank u for u help Marcus Abrahão

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            Saksida Bojan wrote:

            mabrahao wrote: static constructor can be useful No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

            This turns out not to be the case: Static Constructor[^]

            All those who believe in psycho kinesis, raise my hand.

            S Offline
            S Offline
            Saksida Bojan
            wrote on last edited by
            #6

            Thats good to know. I didn't even think it was possible

            1 Reply Last reply
            0
            • M mabrahao

              I am learning C# and OOP, i just cant understand how a static constructor can be useful... can someone please help me with this?? if possible, can u give a simple example? thank you very much... Marcus Abrahão Thank you all very much for your help

              modified on Wednesday, January 6, 2010 7:12 AM

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #7

              If you have a static class, or there is init for the class which must be done once per application (rather than done once for each instance of the class) then use a static constructor. See here: Static Constructor[^]

              All those who believe in psycho kinesis, raise my hand.

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              M 1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                If you have a static class, or there is init for the class which must be done once per application (rather than done once for each instance of the class) then use a static constructor. See here: Static Constructor[^]

                All those who believe in psycho kinesis, raise my hand.

                M Offline
                M Offline
                mabrahao
                wrote on last edited by
                #8

                Thank you, this was helpful Marcus Abrahão

                1 Reply Last reply
                0
                • V V 0

                  Have a look on MSDN[^] Hope this helps.

                  V.
                  Stop smoking so you can: Enjoy longer the money you save. Moviereview Archive

                  M Offline
                  M Offline
                  mabrahao
                  wrote on last edited by
                  #9

                  Thank you Marcus Abrahão

                  1 Reply Last reply
                  0
                  • S Saksida Bojan

                    mabrahao wrote:

                    static constructor can be useful

                    No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

                    public class Test
                    {
                    // Constructor
                    public Test(){}

                    public static Color GetColor()
                    {
                    return Color.White;
                    }
                    }

                    // somewher in your app

                    Color c = Test.GetColor(); // Test t = New Test() was never called.

                    P Offline
                    P Offline
                    Pete OHanlon
                    wrote on last edited by
                    #10

                    Saksida Bojan wrote:

                    No such thing.

                    What are you talking about? Of course there is. You might find reviewing this[^] useful.

                    "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                    As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                    My blog | My articles | MoXAML PowerToys | Onyx

                    S 1 Reply Last reply
                    0
                    • P Pete OHanlon

                      Saksida Bojan wrote:

                      No such thing.

                      What are you talking about? Of course there is. You might find reviewing this[^] useful.

                      "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                      As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                      My blog | My articles | MoXAML PowerToys | Onyx

                      S Offline
                      S Offline
                      Saksida Bojan
                      wrote on last edited by
                      #11

                      I didn't know it was even possible.

                      1 Reply Last reply
                      0
                      • S Saksida Bojan

                        mabrahao wrote:

                        static constructor can be useful

                        No such thing. static is usefull if you call function without intilizing class. If you intilize, constructor is called

                        public class Test
                        {
                        // Constructor
                        public Test(){}

                        public static Color GetColor()
                        {
                        return Color.White;
                        }
                        }

                        // somewher in your app

                        Color c = Test.GetColor(); // Test t = New Test() was never called.

                        D Offline
                        D Offline
                        dojohansen
                        wrote on last edited by
                        #12

                        I wouldn't use the terminology "static constructor" (as ALL constructors are NECESSARILY static - you cannot invoke an instance method until you've constructed an intance). But there certainly is something that (in C#) uses the keyword "static" followed by same syntax as a constructor - the class initializer. Class initializers can be used if you want to perform initialization of some kind once before a type can be used. For example, let's say you are making a bookmaker system. The prices (odds) may vary from 1.01 to 1000, but not everything in between is legal. Instead you have something like this:

                        From To Increment
                        1.01 2.00 0.01
                        2.02 4.00 0.02
                        4.04 10.00 0.05
                        ....
                        500 1000 10

                        You could use an Int32 to store the integral number of 1/100 units, i.e. 125 for 1.25, and cover more than the range you need. But if there are only 256 legal prices you could store it in just a byte. This could make a big difference when tens of thousands of transactions per hour are to be handled, especially in terms of writing data to a database. Anyway, it doesn't really matter for our purposes whether or not the representation is useful! The point is this is a good candidate for a type initializer. Given a byte value of 135, we need to find price number 135 of the legal prices. So we can equip the class with an array and initialize the type before it's used like this:

                        public class OddsPrice
                        {
                        // --- Class members --- //

                        // Legal prices in ascending order.
                        static int[] priceArray;

                        // Type initializer: Initializes price array.
                        static OddsPrice()
                        {
                        priceArray = new int[256];
                        int price = 100; // cents
                        int i = 0;
                        while ((price += 1) <= 200) priceArray[i++] = price;
                        while ((price += 2) <= 400) priceArray[i++] = price;
                        ...
                        }

                        // --- Instance members --- //

                        // Byte representation of value: Index in ordered set of legal values.
                        byte value;

                        // Value in cents
                        public int Value
                        {
                        get { return priceArray[value]; }
                        }
                        }

                        The type initializer will be called automatically at an undefined time (in current implementations of the CLR I believe it happens when the assembly is loaded, but the spec says undefined so don't assume anything) prior to the type being used at run-time. The advantage is that you do not need to handle any thread-syncing to ensure it runs once and only once and before anything else on the type can be used.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups