It is possible assign default value to property like below?
//private int myInteger = 12345; // I don't want this local variable
but I want to assign a default value to below one
Public int MyInteger
{
get;
set;
}
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Selva GanapathyRank #560 · 4.3K reputationPosted Nov 26, 2014, 12:39 AM EST
Hi Mike,
If you used c# 6.0 the please make use of auto property because C# 6.0 introduces a feature of setting default value with out local variable as below
VulpesRank #55 · 29.2K reputationPosted Nov 26, 2014, 1:51 AM EST
However, the final version of that (and Visual Studio 2015) is still some time away.
In the meantime all you can do is to give automatic properties a default value in the constructor:
Notice that if you try to do something similar in a struct:
you'll get these compiler errors:
Joginder BangerRank #360 · 7K reputationPosted Nov 26, 2014, 12:30 AM EST
private int myInteger = 12345;
Public int _MyInteger
{
get{return myInteger ;}
set{myInteger=value; }
}
Selva GanapathyRank #560 · 4.3K reputationPosted Nov 26, 2014, 12:38 AM EST
Hi Mike,
If you used c# 6.0 the please make use of auto property because C# 6.0 introduces a feature of setting default value with out local variable as below
Manish Kumar ChoudharyRank #339 · 7.4K reputationPosted Nov 26, 2014, 12:44 AM EST
you can also use
public int X { get; set; } = x; // C# 6 or higher
or
private int x= 12345;
Public int _X
{
get{return x;}
set{x=value; }
}
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts