I have a function in a controller, and I receive the information for a form. I have this code:
public Actionresult functionOne(string a, string b, string c = "foo" )
I tried to convert this to a class like
public class bar
{
public string a {get;set;}
public string b {get;set;}
public string c {get;set;}
}
and receive them as a object
public Actionresult functionOne(bar b)
Also I tried to put the defaultvalue in 'c' but is not working, I tried this:
public class bar
{
public string a {get;set;}
public string b {get;set;}
[System.ComponentModel.DefaultValue("foo")]
public string c {get;set;}
}
Nothing happened with that, I receive it as null
also I tried
public class bar
{
public string a {get;set;}
public string b {get;set;}
public string c
{
get
{
return c;
}
set
{
c="foo"; //I also tried with value
}
}
}
What should I do to write this default value?
If you are using C# 6 you can do this:
public class Bar {
public string a { get; set; }
public string b { get; set; }
public string c { get; set; } = "foo";
}
Otherwise you can do this:
public class Bar {
public string a { get; set; }
public string b { get; set; }
private string _c = "foo";
public string c
{
get
{
return _c;
}
set
{
_c = value;
}
}
}
1) Use the object's constructor:
public class bar
{
public bar()
{
c = "foo";
}
public string a {get;set;}
public string b {get;set;}
public string c {get;set;}
}
2) Utilize the new auto property default value. Note that this is for C# 6+:
public class bar
{
public string a {get;set;}
public string b {get;set;}
public string c {get;set;} = "foo";
}
3) Use a backing field
public class bar
{
var _c = "foo";
public string a {get;set;}
public string b {get;set;}
public string c {
get {return _c;}
set {_c = value;}
}
}
4) Use the Null Coalescing Operator check
public class bar
{
string _c = null;
public string a {get;set;}
public string b {get;set;}
public string c {
get {return _c ?? "foo";}
set {_c = value;}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With