Properties getter and setter
In this chapter you will learn:
- Add statement to the getter and setter of a property
- Put logic to property setter
- 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:
Home » C# Tutorial » Class