0

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

Miguel Moura
  • 28,129
  • 59
  • 187
  • 356

5 Answers5

3

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

1

Just set the default value in the class constructor.

public class MyClass
{

     public MyClass()
     {
        MyProperty = 22;
     }


     public int MyProperty { get; set; }

     ...
}
Roy Dictus
  • 30,703
  • 5
  • 56
  • 69
1

You can create a backing field:

private string _url = "myUrl"

public String Url
{
    get { return _url; }
    set { _url = value; }
}
Michael Mairegger
  • 5,984
  • 27
  • 39
0

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.

NoviceProgrammer
  • 3,189
  • 1
  • 19
  • 31
0

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; }
}
anar khalilov
  • 15,134
  • 9
  • 43
  • 58