Set default value in C # class constructor

I need a set of default values ​​and access to them and their access to various pages .. In fact, can I set the default value in the class constructor as follows? What is the correct 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;

}
+5
source share
3 answers

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

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

, : http://blogs.msdn.com/b/brada/archive/2004/04/17/115300.aspx

+9

, , :

class ProfitVals
{
    public static double HiProfit { ... }

    static ProfitVals()  // static ctor
    {
       HiProfit = 0.09;
    }
}

: private/public .

+6

You are almost there, you just need to use the constructor .

public class ProfitVals {
    private static double _hiprofit;

    public static Double HiProfit
    {
        get { return _hiprofit; }

        set { _hiprofit = value; }
    }

    public ProfitVals() {
        // assign default value
        HiProfit = 0.09;
    }
}
+1
source

All Articles