C# Properties

Description

Properties are fields with logics. C# uses get and set keywords to declare a property.

A property consists of a name along with get and set accessors. The accessors are used to get and set the value of a variable.

Syntax

The general form of a property is shown here:


type propertyName {/*from w  w  w  . j a  v a2  s.  c o  m*/
    get {
        // get accessor code
    }
    
    set {
        // set accessor code
    }
}

The following code shows how to create properties.

We define a field, age, to hold the value. Then we expose the field with a property named Age. When assigning value to Age the set part is called. When reading value from Age the get part is called.


private int age; 
              /*from w w  w. j a  v a2s.  c  om*/
public int Age  
{ 
   get 
   { 
      return age; 
   } 
   set 
   { 
      age = value; 
   }  
} 

Example

Example for C# Properties


using System;// ww  w .  j  a v  a2  s .c  om
class Rectangle{
   private int width;
   
   public int Width{
      get{
         return width;
      }
      set{
         width = value;
      }
   }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        r.Width = 5;
        Console.WriteLine(r.Width);
    }
}

The output:

Note

The get accessor runs when the property is read. It must return a value of the property's type.

The set accessor is run when the property is assigned. It has an implicit parameter named value of the property's type that you typically assign to a private field.

Properties give the implementer complete control over getting and setting its value.

Example 2

The following code adds log message for property getter and setter. Whenever we access the property it will output message telling us the property is being accessed.


public class A
{//from w  w  w  . j a va  2  s  . com
   private int myValue;

   public int MyValue
   {
      get
      {
         System.Console.WriteLine( "Getting myValue" );
         return myValue;
      }

      set
      {
         System.Console.WriteLine( "Setting myValue" );
         myValue = value;
      }
   }
}

public class MainClass
{
   static void Main()
   {
      A obj = new A();

      obj.MyValue = 1;
      System.Console.WriteLine( "obj.Value = {0}",
                                obj.MyValue );
   }
}

The code above generates the following result.

Example 3

The following code adds more logic to property setter.


using System;//w ww. j a va2s  . c o  m
using System.Collections.Generic;
using System.Text;

class MainClass
{
    static void Main(string[] args)
    {
        Person person = new Person();

        person.SetName("A", "B");

        Console.WriteLine("The person's full name is {0}",person.FullName);
        person.FullName = "A b c";
        Console.WriteLine("The person's full name is {0}",person.FullName);
    }
}
class Person
{
    private string _lastname;
    private string _firstname;

    public void SetName(string lastname, string firstname)
    {
        _lastname = lastname;
        _firstname = firstname;
    }
    public string FullName
    {
        get
        {
            return _firstname + " " + _lastname;
        }
        set
        {
            string[] names = value.Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries);
            _firstname = names[0];
            _lastname = names[names.Length - 1];

        }
    }
}

The code above generates the following result.

Example 4

As what we can do inside a property we can throw exception out of a property logic.


using System;//w w w.  ja  v a 2s .  c  o  m


public class MyClass
{
    public readonly string Name;
    private int intVal;

    public int Val
    {
        get
        {
            return intVal;
        }
        set
        {
            if (value >= 0 && value <= 10)
                intVal = value;
            else
                throw (new ArgumentOutOfRangeException("Val", value,"Val must be assigned a value between 0 and 10."));
        }
    }
    public override string ToString()
    {
        return "Name: " + Name + "\nVal: " + Val;
    }

    private MyClass() : this("Default Name")
    {
    }
    public MyClass(string newName)
    {
        Name = newName;
        intVal = 0;
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass myObj = new MyClass("My Object");
        Console.WriteLine("myObj created.");
        for (int i = -1; i <= 0; i++)
        {
            try
            {
                myObj.Val = i;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0} thrown.", e.GetType().FullName);
                Console.WriteLine("Message:\n\"{0}\"", e.Message);
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor