I have the following class:
public class Topic
{
public string Topic { get; set; }
public string Description { get; set; }
public int Count { get; set; }
}
I would like to have the Count always set to zero when the class is created with the following:
var abc = new Topic {
Topic = "test1",
Description = "description1"
}
I am a bit confused with constructor. Is this possible or do I need to specify Topic, Description and Count when I create abc?
The default value of an int is 0.
All value types have default values as they can't be null.
See Initializing Value Types on this MSDN page.
You have a few different options.
1) int defaults to zero so it will be zero if you dont initialize it.
2) you can use a constructor
public Topic(){ Count = 0;}
3) You can use a backing field instead of auto-property and initialize that to zero
private int _count = 0;
public int Count {
get {return _count}
set {_count = value; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With