Pass value by reference with read only value
/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
using System;
namespace PassByRef
{
public class Time
{
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// Property (read only)
public int GetHour()
{
return Hour;
}
// public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
Month, Date, Year, Hour, Minute, Second);
}
// takes references to ints
public void GetTime(ref int h, ref int m, ref int s)
{
h = Hour;
m = Minute;
s = Second;
}
// constructor
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}
public class TesterPassByRef
{
public void Run()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime();
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
// pass the ints by reference
t.GetTime(ref theHour, ref theMinute, ref theSecond);
System.Console.WriteLine("Current time: {0}:{1}:{2}",
theHour, theMinute, theSecond);
}
static void Main()
{
TesterPassByRef t = new TesterPassByRef();
t.Run();
}
}
}
Related examples in the same category