tester
tester

Reputation: 23189

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

so for a user control, I have

public int Count { get; set; }

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?

Upvotes: 2

Views: 313

Answers (7)

Hasanain
Hasanain

Reputation: 935

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?

Upvotes: 1

Marius Schulz
Marius Schulz

Reputation: 16470

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; }
}

Upvotes: 1

user166390
user166390

Reputation:

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.

Upvotes: 1

Colin Mackay
Colin Mackay

Reputation: 19185

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

public MyClass()
{
    Count = 15;
}

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93474

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.

Upvotes: 1

manji
manji

Reputation: 47968

In the constructor of the userControl

public YourUserControl(){
   Count = 15;
}

Upvotes: 7

Reed Copsey
Reed Copsey

Reputation: 564891

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; } 
    }

Upvotes: 4

Related Questions