Paviel Kraskoŭski
Paviel Kraskoŭski

Reputation: 1419

Should I set properties explicitly?

We have class:

public class Test
{
     public int A { get; set; }
}

And then we create an instance of this class:

Test test = new Test();

The A property should be 0, when we create an object. Should I set this property to 0 explicitly in constructor of Test?

public Test()
{
     A = 0;
}

Upvotes: 1

Views: 95

Answers (3)

Maxim Fleitling
Maxim Fleitling

Reputation: 562

Yes this is the current right approach. In C# 6 you have a possibility to set it directly.

public int A { get; set; } = 0;

You of cause can have a private field (backing field) which is initially set to 0.

Of cause consider that int is 0 by default. So if you need to set it to some different value it would be the right approach.

Upvotes: 0

Darren
Darren

Reputation: 70718

public class Test
{
     public A { get; set; }
}

Will not work as you have not specified the data type for variable A.

I assume you mean:

public class Test
{
     public int A { get; set; }
}

By default A will be 0 when a new instance of Test is instantiated.

As an additional note, a constructor is a good place to initialize variables, however in this case I would not use it as an access point to set variables to 0 when the compiler will handle that for you automatically.

Upvotes: 2

Raja Nadar
Raja Nadar

Reputation: 9489

assuming you meant,

 public int A { get; set; }

no, you don't need to set the default values. the compiler won't complain or anything.

if you still want to, set it for clarity of code. it helps the reader understand that you clearly want the initial value to be zero and removes any guess work. people normally do this, if 0 has a business meaning or for clarity of code.

Upvotes: 1

Related Questions