Properties getter and setter

In this chapter you will learn:

  1. Add statement to the getter and setter of a property
  2. Put logic to property setter
  3. throw Exception from property setting

Getter and setter

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 j  av a2 s .c o  m*/
   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.

More logic to setter

The following code adds more logic to property setter.

using System;//j a  va 2  s.co  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.

Exception from property

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

using System;/*  j a  va2s.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);
            }
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to control the accessibilities for properties getter and setter
Home » C# Tutorial » Class
Classes and Structs
Encapsulation
Class and Struct Accessibility
Members
Static Members
Class
Class instance variables
Class instance Methods
Class Inheritance
Class constructor
Default constructors
Parameters of constructors
Constructor overloading
Static Constructor
Destructor
Override destructor
new operator
Class field
Static Fields
Read only field
Field default value
const value
Abstract class
Static Class
Partial type
Methods
Method local variable
Method Overloading
Method overloading with ref and out
Type conversion and method overloading
Error in Method overloading
virtual methods
Override methods
Method Parameter
Pass parameters
ref parameters
out parameters
Variable parameter length
Optional parameters
Named parameters
static method
function Return
Recursive methods
Virtual methods and polymorphism
Cast
Shadow inherited members
Seal a member
this keyword
base keyword
base and name hiding
Access Specifiers
private
public
protected
internal
Indexer
String type indexer
Multidimensional indexer
Indexer overloading
Indexer to append
Indexer logic
Properties
Properties getter and setter
Accessibilities of properties
Automatic properties
Read only and write only property
Virtual properties
Abstract Properties
Static Properties
interface
interface implementation
Explicit interface implementation
Interface inheritance
Indexer in an interface
Interface Properties
struct and interface
virtual interface implementation
as operator
is operator
null reference
Nested classes
object class
ToString method
GetHashCode
Object initialization
Extension method
Struct Instances vs. Class Instances