Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value C# class [duplicate]

Tags:

c#

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?

like image 608
TiGreX Avatar asked Nov 27 '22 21:11

TiGreX


2 Answers

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;
        }
    }
}
like image 144
Anish Patel Avatar answered Nov 29 '22 13:11

Anish Patel


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;}
        }
    }
like image 29
JasonWilczak Avatar answered Nov 29 '22 11:11

JasonWilczak