简体   繁体   中英

Assign default value to property

I have the following class property:

public String Url { get; set; }

I would like it to return a default value in case it wasn't defined.

I do not want to return String.Empty when it wasn't defined.

I am using the NET 4.5.

What is the best way to do this?

Thank You, Miguel

well to be honest i dont know if it is the best answeer and well this is my first asweer here, but that is besides the point. i whould do it like this

class Class1
{
    string sUrl = "www.google.com";
    public string Url
    {
        get
        {
            return sUrl;
        }
        set
        {
            sUrl = value;
        }
    }
}

now you have a string value behind the property that has a default of www.google.com

hope this helps

Just set the default value in the class constructor.

public class MyClass
{

     public MyClass()
     {
        MyProperty = 22;
     }


     public int MyProperty { get; set; }

     ...
}

You can create a backing field:

private string _url = "myUrl"

public String Url
{
    get { return _url; }
    set { _url = value; }
}

For a non static field, we can only set the default value after the object is constructed. Even when we inline a default value, the property is initialized after construction.

For automatic properties, constructor is the best place to initialize. Maybe you can do it in the default constructor and then have additional constructors as required.

Another option would be to use reflection - but that is more than an overkill.

You can initialize your property inside your default constructor AND do not forget to call the default constructor inside other constructors (in this example MyClass(int) ), otherwise the field will not be initialized.

class MyClass
{
    public MyClass()
    {
        this.Url = "http://www.google.com";
    }

    public MyClass(int x)
        : this()
    {
    }

    public String Url { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM