set default value in class constructor C#

CraigJSte picture CraigJSte · Mar 9, 2011 · Viewed 9.2k times · Source

I need a default value set and many different pages access and update..initially can I set the default value in the class constructor like this? What is the proper way to do this in C# .NET?

public class ProfitVals
{

    private static double _hiprofit;

    public static Double HiProfit
    {
        get { return _hiprofit; }

        set { _hiprofit = value; }
    }

    // assign default value

    HiProfit = 0.09;

}

Answer

Mark Sowul picture Mark Sowul · Mar 9, 2011

You can put it in the declaration: private static double _hiprofit = 0.09; Or if it's a more complicated initialization you can do it in the static constructor:

   private static double _hiprofit; 
   static ProfitVals() 
   {
      _hiprofit = 0.09;
   }

The former is preferred as the latter pays a performance penalty: http://blogs.msdn.com/b/brada/archive/2004/04/17/115300.aspx