Wednesday, July 10, 2013

Set Default Value for the property C#.

See the different way to set default value for the property below

Namespace
using System.ComponentModel;

Source Code
//Set default value for the property using Default Attribute
public class SetDefaultPropertyValueByAttribute
{
   [DefaultValue(100)]
   public int Id { get; set; }

   [DefaultValue("Ritesh")]
   public string Name { get; set; }

   [DefaultValue(true)]
   public bool IsBool { get; set; }

   [DefaultValue("01/01/2013")]
   public DateTime DateOfBirth { get; set; }

}

We normally set default value to the property like below

Namespace
using System;

Source Code

//Set default value for the property using variable declaration
public class SetDefaultPropertyValueByVariable
{
   private int id = 100;
   private string name = "Ritesh";
   private bool isBool = true;
   private DateTime dateOfBirth = DateTime.UtcNow;

   public int Id
   {
      get { return this.id; }
      set { this.id = value; }
   }

   public string Name
   {
      get { return this.name; }
      set { this.name = value; }
   }

   public bool IsBool
   {
      get { return this.isBool; }
      set { this.isBool = value; }
   }

   public DateTime DateOfBirth
   {
       get { return this.dateOfBirth; }
       set { this.dateOfBirth = value; }
    }
 }

No comments: