6

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;

}
4
  • 1
    why not just do it in the declaration: private static double _hiprofit = 0.09D; Commented Mar 9, 2011 at 20:16
  • is that the best / proper way to do it?? that looks fine to me. Commented Mar 9, 2011 at 20:17
  • it is personal preference IMO, both are viable approaches Commented Mar 9, 2011 at 20:18
  • There are performance implications. Commented Mar 9, 2011 at 20:22

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

Comments

6

No, you would have to surround the assignment to the property with an actual static constructor like so:

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

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

Note: a static constructor can not be declared private/public and cannot have parameters.

Comments

1

You're almost there, you just need to use a 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;
    }
}

6 Comments

That is an instance constructor.
this won't work - now every time you create a ProfitVals instance HiProfit is set to its default value.
@Henk - yes it is; I thought that's what the OP was asking for? @BrokenGlass - given the OP's statement "I need a default value set", why is this a breaking implementation?
@48klo, can you think of a scenario for a static (shared) property that is reset by each instance?
the default values is only set until its changed .. but it should not reset when the class is accessed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.