Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Class constructor default value question

Tags:

c#

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?

like image 613
Geraldo Avatar asked Jun 14 '11 12:06

Geraldo


2 Answers

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.

like image 163
Oded Avatar answered Oct 20 '22 19:10

Oded


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; }
 }
like image 30
Bala R Avatar answered Oct 20 '22 21:10

Bala R