RainingChain
RainingChain

Reputation: 7782

C#: Define Class Variable, Default Value and Get Set Not Working?

I'm trying to do something like public decimal hp = 1000; { get; set; } but it's not working...

I do know the conventional way to do this would be to create 2 separated variables, one private and one public but is it possible to set a default value and get/set with the same variable? Without having to put the default value in the actual constructor function?

Upvotes: 2

Views: 529

Answers (3)

comdiv
comdiv

Reputation: 951

Syntax U try in your question will be provided in C# 6

[http://odetocode.com/blogs/scott/archive/2014/08/04/c-6-0-features-part-i-property-initializers.aspx]

But with a little difference:

public decimal hp { get; set; } = 1000;

Upvotes: 3

Jonesopolis
Jonesopolis

Reputation: 25370

This isn't possible.

But it will be soon! Take a look here

Auto-Properties will get initializers in C# 6.0. The syntax will be very close to what you were getting at:

public string MyString { get; set; } = "Hello, World!";

There's a lot of other cool stuff to be implemented too!

Upvotes: 2

Claudio Redi
Claudio Redi

Reputation: 68440

No, it's not possible. Auto-properties can't be initialized inline.

Upvotes: 1

Related Questions