0
class Log
{
 public int LocationId { set { value = 1; } get; }
}

Will this set the default value for Log as 1 when i use like this: Log l=new log(); Console.Writeline(l.LocationId);

?

I am aware of the normal way of using a property but will this also work?

Milee
  • 1,191
  • 1
  • 11
  • 29
  • > http://stackoverflow.com/questions/40730/how-do-you-give-a-c-sharp-auto-property-a-default-value > > http://stackoverflow.com/questions/2272469/how-to-get-the-default-value-of-an-object-property – Sadaf Apr 12 '12 at 06:59

2 Answers2

5

The proper way to do it is in the constructor:

class Log {
    public Log() {
        LocationId = 1;
    }

    public int LocationId { set; get; }
}
ionden
  • 12,536
  • 1
  • 45
  • 37
4

No, you should do like this:

class Log
{
   private int locationID = 1; //This is a default value
   public int LocationId 
   { 
      set 
      { 
          locationID = value; 
      } 
      get 
      {
          return locationID;
      } 
   }
}
Tigran
  • 61,654
  • 8
  • 86
  • 123