C# Properties

In this chapter you will learn:

  1. What are C# Properties
  2. How to create C# Properties
  3. Example for C# Properties
  4. Note for properties
  5. Add statement to the getter and setter of a property
  6. Put logic to property setter
  7. throw Exception from property setting

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 {/* w  ww  .ja v a 2s. com*/
    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 va 2 s  .c o  m*/
public int Age  
{ 
   get 
   { 
      return age; 
   } 
   set 
   { 
      age = value; 
   }  
} 

Example

Example for C# Properties


using System;/*from   w  w  w .j a  va  2  s .  c o m*/
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
{//  w ww.  j  a  v a  2s  .c om
   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;//from w  w w .  ja va 2  s.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;//from  w w w  .  jav a 2  s .c  om


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.

Next chapter...

What you will learn in the next chapter:

  1. What are C# property accessor modifiers
  2. Example for C# property accessor modifiers
Home »
  C# Tutorial »
    C# Types »
      C# Properties
C# Properties
C# property accessor modifiers
C# read or write only property
C# Automatic properties
C# Static Properties
C# Abstract Properties