开发者

How do I set a property to a default value in C#?

开发者 https://www.devze.com 2023-03-11 10:56 出处:网络
so for a user control, I have public int Count { get; set; } 开发者_JAVA技巧so that I can use this.Count in another method. The trouble is, I want to set a default for Count to something like 15. H

so for a user control, I have

public int Count { get; set; }

开发者_JAVA技巧so that I can use this.Count in another method. The trouble is, I want to set a default for Count to something like 15. How do I set defaults?


In the constructor of the userControl

public YourUserControl(){
   Count = 15;
}


You will need to set it in the constructor of your class.

For example:

public partial class YourControl : UserControl
{
    public int Count { get; set; }

    public YourControl()
    {
         InitializeComponent();

         // Set your default
         this.Count = 15;
    }
}

Alternatively, if you use a backing field, you can set it inline on the field:

public partial class YourControl : UserControl
{
    private int count = 15;
    public int Count 
    {
        get { return this.count; } 
        set { this.count = value; } 
    }


If you want the object that creates your control to set the default, then they can use a property initializer when they new the control. If you want to set a default for the control, then you would set those defaults in the constructor.


You set the default values for automatic properties in the constructor of the class.

public MyClass()
{
    Count = 15;
}


Or alternatively to setting the value in the constructor, which will likely work just fine here, use the long approach.

int _count = 15;
public int Count {
  get { return _count; }
  set { _count = value; }
}

Sometimes this way is useful if the appropriate constructor is not called for some reason (such as some Serialization/Activation techniques).

Happy coding.


Instead of using an auto implemented property you can write your own property based on an underlying field containing your default value:

private int _count = 15;
public int Count
{
    get { return _count; }
    set { _count = value; }
}


You can use the DefaultValueAttribute. More info here: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

This question is a possible duplicate: How do you give a C# Auto-Property a default value?

0

精彩评论

暂无评论...
验证码 换一张
取 消