Properties in C#
Feb 25, 2017 01:00 0 Comments C# (C-Sharp) Neelima

                                                         Properties in C#

Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated.

Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.

For example, let us have a class named Student, with private fields for age, name, and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields.

 

Accessors

The accessor of a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. For example −

// Declare a Code property of type string:

public string Code {

   get {

      return code;

   }

   set {

      code = value;

   }

}

 // Declare a Name property of type string:

public string Name {

   get {

      return name;

   }

   set {

      name = value;

   }

}

 // Declare an Age property of type int:

public int Age {

   get {

      return age;

   }

   set {

      age = value;

   }

}

Example

The following example demonstrates the use of properties −

using System;

namespace propertiestutorial {

   class Student {

      private string code = "N.A";

      private string name = "not known";

      private int age = 0;

     

      // Declare a Code property of type string:

      public string Code {

         get {

            return code;

         }

         set {

            code = value;

         }

      }

     

      // Declare a Name property of type string:

      public string Name {

         get {

            return name;

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect