Properties in C#

Properties in C# can be used to set or get the value of an attribute. Suppose you have a class called Person which has the attributes name and age.

class Person {

  String name;
  int age;

  public Person(String name, int age){
    this.name = name;
    this.age = age;
  }
}

The attributes of the Person class are private in this case. They wouldn’t be accessible when an instance of Person is created. The properties Name and Age could be created for getting and setting the values of the attributes. Besides that, the Age property could be validated before setting the value.

class Person {

  String name;
  int age;

  public Person(String name, int age){
    this.name = name;
    this.age = age;
  }

  public String Name { get; set; }

  public int Age {
    get {
      return this.age;
    }

    set {
      if(value >= 0 && value <= 150){ // Our Person can get quite old!
        this.age = value;
      } else {
         throw new Exception("Invalid age supplied");
      }
    }
  }

}

 

This entry was posted in C# and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?