none
How to initialize static variable RRS feed

  • Question

  • Hi, 

    I want to initialize a class's static variable within the class definition, how can I do that? 

    Or, why the following doesn't work?

    Thanks

        class StaticCustomer
        {
            // Auto-Impl Properties for trivial get and set 
            public static double TotalPurchases { get; set; }
            public static string Name { get; set; }
            public static int CustomerID { get; set; }
    
            // Constructor 
            public StaticCustomer()
            {
                TotalPurchases = 4987.63;
                Name = "Northwind";
                CustomerID = 90108;
            }
    
            // .. Additional methods, events, etc.
        }

    Tuesday, December 4, 2012 5:42 PM

Answers

  • You can use static constructors to do so. Example:

    public class SomeClass
    {
        // more variables...
        static readonly int staticValue; // readonly value (can only be set once)
    
        static SomeClass()
        {
            staticValue = 42;
            SomeComplexProperty = new OtherClass();
            SomeComplexProperty.DoSomething(staticValue);
        }
    
        SomeComplexProperty
        {
            // property definition
        }
        // other stuff...
    }


    "Penso, logo existo" - René Descartes
    "A produção de muitas coisas úteis resulta em muitas pessoas inúteis" - Karl Marx
    "Vive como se fosses morrer amanhã, aprende como se fosses viver para sempre" - Mahatma Gandhi

    João Miguel

    • Marked as answer by smetah Tuesday, December 4, 2012 6:00 PM
    Tuesday, December 4, 2012 5:57 PM

All replies

  • // for a constant initial value
    static int x = 2;
    
    


    "Premature optimization is the root of all evil." - Knuth

    If I provoked thought, please click the green arrow

    If I provoked Aha! please click Propose as Answer

    Tuesday, December 4, 2012 5:47 PM
  • // for a constant initial value
    static int x = 2;
    

    Oh, forgot to stress that I need to initialize a class's static Auto-Implemented Properties values. 

    thanks though. 

    Tuesday, December 4, 2012 5:51 PM
  • "Or, why the following doesn't work?"

    What do you mean by doesn't work, are you getting an error? The presented code compiles fine.

    Tuesday, December 4, 2012 5:53 PM
    Moderator
  • You can use static constructors to do so. Example:

    public class SomeClass
    {
        // more variables...
        static readonly int staticValue; // readonly value (can only be set once)
    
        static SomeClass()
        {
            staticValue = 42;
            SomeComplexProperty = new OtherClass();
            SomeComplexProperty.DoSomething(staticValue);
        }
    
        SomeComplexProperty
        {
            // property definition
        }
        // other stuff...
    }


    "Penso, logo existo" - René Descartes
    "A produção de muitas coisas úteis resulta em muitas pessoas inúteis" - Karl Marx
    "Vive como se fosses morrer amanhã, aprende como se fosses viver para sempre" - Mahatma Gandhi

    João Miguel

    • Marked as answer by smetah Tuesday, December 4, 2012 6:00 PM
    Tuesday, December 4, 2012 5:57 PM
  • You can use static constructors to do so. 

    BINGO! Thanks.
    Tuesday, December 4, 2012 5:59 PM
  • You're welcome. BTW, @Mike Danes is right, your code does compile (although it's useless) to assign static values to the same thing in every instance of a class.

    "Penso, logo existo" - René Descartes
    "A produção de muitas coisas úteis resulta em muitas pessoas inúteis" - Karl Marx
    "Vive como se fosses morrer amanhã, aprende como se fosses viver para sempre" - Mahatma Gandhi

    João Miguel


    • Edited by JMCF125 Tuesday, December 4, 2012 6:06 PM adding info
    Tuesday, December 4, 2012 6:03 PM
  • oh, hold on a second, 

        class StaticCustomer
        {
            // Auto-Impl Properties for trivial get and set 
            public static double TotalPurchases { get; set; }
            public static string Name { get; set; }
            public static int CustomerID { get; set; }
    
            // Constructor 
            static StaticCustomer()
            {
                TotalPurchases = 4987.63;
                Name = "Northwind";
                CustomerID = 90108;
            }
    
            // .. Additional methods, events, etc.
        }
    

    Error 1 'StaticCustomer.StaticCustomer()': access modifiers are not allowed on static constructors

    what I'm doing wrong?

    Tuesday, December 4, 2012 6:05 PM
  • [...] access modifiers are not allowed on static constructors [...]

    That's exacly what it means: you can't use access modifiers on static constructors. You can't use, for example, "public static YourClassName() {...}" as a constructor. It wouldn't make sense, because these aren't called by you; they're called when the program starts.

    "Penso, logo existo" - René Descartes
    "A produção de muitas coisas úteis resulta em muitas pessoas inúteis" - Karl Marx
    "Vive como se fosses morrer amanhã, aprende como se fosses viver para sempre" - Mahatma Gandhi

    João Miguel

    Tuesday, December 4, 2012 6:11 PM
  • Ok, understood now. 

    Now, how can I fix it to make it working?

    thx

    Tuesday, December 4, 2012 6:14 PM
  • My bad, I thought VS would auto compile for me. 

    after I manually compile it myself, the error went away. 

    Still feel strange that VS would not auto compile for me after I've change my code. 

    Tuesday, December 4, 2012 6:16 PM
  • Remove the access modifier from that constructor.

    João Miguel


    • Edited by JMCF125 Tuesday, December 4, 2012 6:28 PM shortening signature
    Tuesday, December 4, 2012 6:27 PM
  • Do you only intend to have a single customer?  Using static properties, especially for something like CustomerID means that there can ever only be one value which applies to the class.

    Won't you have other customers?  Where will you store their customer id?

    Tuesday, December 4, 2012 6:51 PM