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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Selva GanapathyPosted Nov 26, 2014, 5:39 AM
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
VulpesPosted Nov 26, 2014, 6:51 AM
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:
Manish Kumar ChoudharyPosted Nov 26, 2014, 5:44 AM
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; }
}
Selva GanapathyPosted Nov 26, 2014, 5:38 AM
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
Joginder BangerPosted Nov 26, 2014, 5:30 AM
private int myInteger = 12345;
Public int _MyInteger
{
get{return myInteger ;}
set{myInteger=value; }
}