Miguel Moura
Miguel Moura

Reputation: 39374

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

Upvotes: 0

Views: 321

Answers (5)

anar khalilov
anar khalilov

Reputation: 17498

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; }
}

Upvotes: 0

NoviceProgrammer
NoviceProgrammer

Reputation: 3365

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.

Upvotes: 0

user3061078
user3061078

Reputation:

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

Upvotes: 3

Michael Mairegger
Michael Mairegger

Reputation: 7301

You can create a backing field:

private string _url = "myUrl"

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

Upvotes: 1

Roy Dictus
Roy Dictus

Reputation: 33139

Just set the default value in the class constructor.

public class MyClass
{

     public MyClass()
     {
        MyProperty = 22;
     }


     public int MyProperty { get; set; }

     ...
}

Upvotes: 1

Related Questions