4.1 DateTime Class
To get the dates and time we use the DateTime class. The DateTime class stores
both a full date and the full time. The two static members are Now and Today. Now
contains the date and time for the moment the call is made. Today returns the current
date. For formatting we could use d which would be the short date mm/dd/yyyy,
for example 9/24/2005 and D would be Saturday, September 24, 2005.
// myDate.cs
using System;
class myDate
{
public static void Main()
{
DateTime dt = DateTime.Now;
Console.WriteLine("Date Time output: {0}",dt); // 7/29/2006 3:18:03 PM
string s = dt.ToString();
Console.WriteLine("s = " + s);
DateTime today = DateTime.Today;
Console.WriteLine("Today is: {0}",today);
Console.WriteLine("Time output: {0}:{1}:{2}",dt.Hour,dt.Minute,dt.Second);
Console.WriteLine("Date output: {0}\\{1}\\{2}",dt.Year,dt.Month,dt.Day);
DateTime m1 = DateTime.Now;
int milli1 = m1.Millisecond;
Console.WriteLine("milli1 = " + milli1);
for(uint j=0;j<10000000;j++)
{ j = j*2; j = j/2; j++; j--; }
48
4.2. ARRAY CLASS 49
DateTime m2 = DateTime.Now;
int milli2 = m2.Millisecond;
Console.WriteLine("milli2 = " + milli2);
int diff = milli2 - milli1;
Console.WriteLine("diff = " + diff);
// Formats
DateTime currTime = DateTime.Now;
Console.WriteLine("d: {0:d}",currTime); // 9/24/2005
Console.WriteLine("D: {0:D}",currTime); // Saturday, September 24, 2005
}
}
4.2 Array Class
The Array class
class Array : IClonable, ICollection, IEnumerable, IList
cotains methods for manipulations of arrays. For example
int BinarySearch(Array array,object value);
int BinarySearch(Array array,int index,int length,object value);
public virtual object Clone();
void Clear(Array array,int index,int length);
void Copy(Array source,Array destination,int length);
int IndexOf(Array array,object value);
void Reverse(Array array);
void Reverse(Array array,int index,int length);
An example is
// MyArray.cs
using System;
//using System.Collections.IList;
class MyArray
{
public static void Main()
{
int[] a1 = { 669, 56, 45, 877, 123, 456, 777 };
int p1 = Array.BinarySearch(a1,877);
Console.WriteLine("p1: {0}", p1);
50 CHAPTER 4. BUILT-IN CLASSES
string[] s1 = new string[] { "aaba", "baaba", "alla", "ana" };
Array.Sort(s1);
for(int i=0;i
{ Console.WriteLine("s1[" + i + "]=" + s1[i]); }
Array.Reverse(s1);
for(int i=0;i
{ Console.WriteLine("s1[" + i + "]=" + s1[i]); }
Array.Clear(a1,3,2);
for(int i=0;i
{ Console.WriteLine("a1[" + i + "]=" + a1[i]); }
int j = Array.IndexOf(a1,123);
Console.WriteLine("j = " + j); // j = -1 why?
}
}
4.3 ArrayList Class
An ArrayList is used in situations where we want an array-like list, but cannot
restrict the number of elements it may contain. The method Add() adds an element
to the list. An application of the ArrayList class is given below.
// arraylist.cs
using System;
using System.Collections;
class arraylist
{
public static void Main(string[] arg)
{
ArrayList alist = new ArrayList();
foreach(string s in arg) alist.Add(s);
for(int i=0;i
{
Console.Write("{0}",alist[i]);
}
Console.Write("\n");
Console.Write("Argument Count:{0}\n",alist.Count);
string s1 = "Xena";
4.4. LISTDICTIONARY CLASS 51
alist.Insert(3,s1);
alist.RemoveAt(1);
ArrayList nlist = new ArrayList();
nlist = alist;
bool test = alist.Equals(nlist);
Console.WriteLine("{0}",test);
} // end main
}
4.4 ListDictionary Class
The ListDictionary class stores a key and a value. The method
public void Add(key,value)
adds an element to the ListDictionary. The method
void Remove(object key);
removes an element in the dictionary.
// Dictionary.cs
using System;
using System.Collections;
using System.Collections.Specialized;
class Dictionary
{
public static void Main()
{
ListDictionary population = new ListDictionary();
population.Add("Johannesburg",9345120);
population.Add("CapeTown",3500500);
population.Add("Durban",550500);
foreach(DictionaryEntry name in population)
{
Console.WriteLine("{0} = {1}",name.Key,name.Value);
}
population.Remove("Durban");
foreach(DictionaryEntry name in population)
{
Console.WriteLine("{0} = {1}",name.Key,name.Value);
52 CHAPTER 4. BUILT-IN CLASSES
}
} // end Main()
}
4.5 Class IEnumerator
An enumerator object implements IEnumerator and IEnumerator < T >, where T
is the yield type of the iterator block. It implements System.IDisposable. Memebers
are MoveNext, Current and Dispose. The method
public virtual IEnumerator GetEnumerator()
returns a System.Collections.IEnumerator for the current instance.
// Enumerator.cs
using System;
using System.Collections;
public class ArrayGetEnumerator
{
public static void Main()
{
string[,] strArry = {{"1","one"}, {"2","two"}, {"3","three"}};
Console.Write("The elements of the array are: ");
IEnumerator sEnum = strArry.GetEnumerator();
while(sEnum.MoveNext())
Console.Write(" {0}",sEnum.Current);
}
}
4.6 Mathematics Class
The Math class is sealed. A sealed class cannot be used for inheritance. Additionally,
all the classes and data members are static, so we cannot create an object of type
Math. Instead, we use the members and methods with the class name. The Math
class also includes two constants, PI and E.
The following table shows a partial list of the Math methods.
4.6. MATHEMATICS CLASS 53
Method Returns Argument Return
Data Type Data Type
Abs(x) Absolute value of x Overloaded Return matches
argument type
Atan(x) Angle in Radians Double Double
whose tangent is x
Cos(x) Cosine of x where x Double Double
is in radians
Exp(x) Value of e raised Double Double
to the power of x
Log(x) Natural log of x, Double Double
where x >= 0
Max(x1, x2) Larger of the two Overloaded Return matches
arguments argument type
Min(x1, x2) Smaller of the two Overloaded Return matches
arguments argument type
Pow(x1, x2) Value of x1 raised Double Double
to the power of x2
Round(x, y) Value of x rounded Overloaded Return matches
to y decimal places
Sin(x) Sine of x where x Double Double
is in radians
Sqrt(x) Square root of x Double Double
where x <= 0
Tan(x) Tangent of x where Double Double
x is in radians
For example, to round a double to 2 significant digits:
double x = 3.1415;
double xr = Math.Round(x,2);
// distance.cs
using System;
class Distance
{
public static void Main()
{
double r = 6371.0;
double alpha1, alpha2, beta1, beta2, temp, theta, distance;
char dir;
string source, dest, line;
Console.WriteLine("Enter the name of the source: ");
source = Console.ReadLine();
54 CHAPTER 4. BUILT-IN CLASSES
Console.WriteLine("Enter the latitude of {0}: ", source);
Console.WriteLine("degrees: ");
line = Console.ReadLine();
beta1 = (double) System.Convert.ToInt32(line);
Console.WriteLine("minutes: ");
line = Console.ReadLine();
temp = (double) System.Convert.ToInt32(line);
beta1 += temp/60.0;
Console.WriteLine("N/S: ");
line = Console.ReadLine();
dir = line[0];
if(dir == ’S’
dir == ’s’) beta1 = -beta1;
Console.WriteLine("Enter the longitude of {0}: ",source);
Console.WriteLine("degrees: ");
line = Console.ReadLine();
alpha1 = (double) System.Convert.ToInt32(line);
Console.WriteLine("minutes: ");
line = Console.ReadLine();
temp = (double) System.Convert.ToInt32(line);
alpha1 += temp/60.0;
Console.WriteLine("W/E: ");
line = Console.ReadLine();
dir = line[0];
if(dir == ’E’
dir == ’e’) alpha1 = -alpha1;
Console.WriteLine("Enter the name of the destination: ");
dest = Console.ReadLine();
Console.WriteLine("Enter the latitude of {0}: ",dest);
Console.WriteLine("degrees: ");
line = Console.ReadLine();
beta2 = (double) System.Convert.ToInt32(line);
Console.WriteLine("minutes: ");
line = Console.ReadLine();
temp = (double) System.Convert.ToInt32(line);
beta2 += temp/60.0;
Console.WriteLine("N/S: ");
line = Console.ReadLine();
dir = line[0];
if(dir == ’S’
dir == ’s’) beta2 = -beta2;
Console.WriteLine("Enter the longitude of {0}: ",dest);
Console.WriteLine("degrees: ");
line = Console.ReadLine();
alpha2 = (double) System.Convert.ToInt32(line);
Console.WriteLine("minutes: ");
line = Console.ReadLine();
temp = (double) System.Convert.ToInt32(line);
4.7. RANDOM CLASS 55
alpha2 += temp/60.0;
Console.WriteLine("W/E: ");
line = Console.ReadLine();
dir = line[0];
if(dir == ’E’
dir == ’e’) alpha2 = -alpha2;
alpha1 *= Math.PI/180.0; alpha2 *= Math.PI/180.0;
beta1 *= Math.PI/180.0; beta2 *= Math.PI/180.0;
temp = Math.Cos(beta1)*Math.Cos(beta2)*Math.Cos(alpha1-alpha2)
+ Math.Sin(beta1)*Math.Sin(beta2);
theta = Math.Acos(temp);
distance = r*theta;
Console.WriteLine("The distance between {0} and {1} is {2} km",
source,dest,distance);
}
}
4.7 Random Class
The next program shows an application of the Random class.
// random.cs
using System;
class LearnRandom
{
public static void Main()
{
Random r = new Random();
Console.WriteLine("Random sequence(no seed,limit 0..int.MaxVal)");
Console.WriteLine();
for(int i=0;i<10;i++)
Console.WriteLine("random no: {0}",r.Next());
Console.WriteLine("Random sequence(no seed,limit 0..10)");
for(int i = 0;i<10;i++)
Console.WriteLine("random no: {0}",r.Next(10));
Console.WriteLine("Random sequence(no seed,limit 50..100)");
for(int i=0;i<10;i++)
Console.WriteLine("random no: {0}",r.Next(50,100));
Console.WriteLine("Random sequence(no seed, limit 0..1)");
for(int i=0;i<10;i++)
Console.WriteLine("random no: {0}",r.NextDouble());
Console.WriteLine("Random sequence in byte array(no seed,limit 0..1)");
byte[] b = new byte[5];
r.NextBytes(b);
56 CHAPTER 4. BUILT-IN CLASSES
for(int i=0;i
Console.WriteLine("random byte: {0}",b[i]);
}
}
4.8 Point Classes
The Point structure represents an ordered pair xy of integers. The PointF structure
represents an ordered pair of floating point x- and y- coordinates that define a point
in a two-dimensional plane.
// pointt.cs
using System;
using System.Windows.Forms;
using System.Drawing;
class PointTest
{
public static void Main()
{
Point p = new Point(23,13);
Console.WriteLine("Our Point is: " + p);
int xcoord = p.X;
int ycoord = p.Y;
Console.WriteLine("The x coordinate is " + xcoord);
Console.WriteLine("The y coordinate is " + ycoord);
Point q = new Point(xcoord,ycoord);
bool b = p.Equals(q);
Console.WriteLine(" the points are equal: " + b);
PointF pF = new PointF((float)23.3333,(float)13.666666666667);
Console.WriteLine("Our Point is: " + pF);
float xcoordF = pF.X;
float ycoordF = pF.Y;
Console.WriteLine("The x coordinate is " + xcoordF);
Console.WriteLine("The y coordinate is " + ycoordF);
PointF qF = new PointF(xcoordF,ycoordF);
b = pF.Equals(qF);
Console.WriteLine(" the points are equal: " + b);
}
}
4.9. CLASS BITARRAY 57
4.9 Class BitArray
For dealing with bit string we use the class BitArray, where 1 is identified with
true and 0 is identified with false. The constructor
BitArray a = new BitArray(16);
sets all elements to false.
// BitArrayTest.cs
using System;
using System.Collections;
public class BitArrayTest
{
static void Main()
{
BitArray a = new BitArray(16);
BitArray b = new BitArray(16);
a[3] = a[4] = a[5] = true;
b[4] = b[5] = b[6] = true;
BitArray c = a.And(b);
Console.WriteLine("Bitarray c");
int i;
for(i=0;i<16; i++)
Console.WriteLine(c[i]);
Console.WriteLine("");
BitArray d = (BitArray) c.Clone();
Console.WriteLine("Clone c into d");
for(i=0;i<16;i++)
Console.WriteLine(d[i]);
BitArray e = a.Not();
Console.WriteLine("Not a");
for(i=0;i<16;i++)
Console.WriteLine("e[" + i + "]=" + e[i]);
a.SetAll(true);
Console.WriteLine("a.SetAll(true)");
for(i=0;i<16;i++)
Console.WriteLine("f[" + i + "]=" + a[i]);
58 CHAPTER 4. BUILT-IN CLASSES
BitArray g = d.Not();
for(i=0;i<16;i++)
Console.WriteLine("g[" + i + "]=" + g[i]);
BitArray f = d.Xor(g);
Console.WriteLine("Xor d to get f");
for(i=0;i<16;i++)
Console.WriteLine("f[" + i + "]=" + f[i]);
}
}
4.10 Object Class
The Object class supports all classes in the .NET Framework class hierarchy and
provides low-level services to derived classes. This is the ultimate superclass of all
classes in the .NET Framework; it is the root of the type hierarchy. The C# syntax
is
[Serializable]
public class Object
Public static (non-instance) members of this type are safe for multithreaded operations.
Instance members are not guaranteed to be thread-safe. Languages typically
do not require a class to declare inheeritance from Object since the inheritance is
implicit.
Since all classes in the .NET Framework are derived from Object, every method
defined in the Object class is available in all objects in the system. Derived classes
can and do override some of these methods, including
Object.Equals - support comparisons between objects
Object.Finalize - performs cleanup operations before an object is
automatically reclaimed
Object.GetHashCode - generates a number corresponding to the value
of the object to support the use of a hash table
Object.ToString - manufactures a human-readable text that describes
an instance of the class
The default constructor is called by derived class constructors to initialize state in
this type. Initializes a new instance of the Object class.
The method GetHashCode() serves as a hash function for a particular type, suitable
for use in hashing algorithms and data structures like a hash table.
4.10. OBJECT CLASS 59
The method GetType() gets the type of the current instance.
The following code compares the current instance with another object.
// object1.cs
using System;
public class object1
{
public static void Main()
{
Object obj1 = new Object();
Object obj2 = new Object();
Console.WriteLine(obj1.Equals(obj2)); // => false
obj2 = obj1;
Console.WriteLine(obj1.Equals(obj2)); // => true
}
}
The following example shows a Point class that overrides the Object.Equals()
method to provide value equality and a class Point3D, which is derived from the
Point class. The Object.Equals() method uses Object.GetType() to determine
whether the run-time types of the two objects are identical.
// object2.cs
using System;
class Point : Object
{
protected int x, y;
public Point() { this.x = 0; this.y = 0; }
public Point(int X,int Y)
{ this.x = X; this.y = Y; }
public override bool Equals(Object obj)
{ // check for null and compare run-time types
if(obj == null
GetType() != obj.GetType()) return false;
Point p = (Point) obj;
return (x == p.x) && (y == p.y);
}
60 CHAPTER 4. BUILT-IN CLASSES
public override int GetHashCode()
{ return x^y; } // ^ XOR operation
} // end class Point
class Point3D : Point
{
int z;
public Point3D(int X,int Y,int Z)
{
this.x = X; this.y = Y; this.z = Z;
}
public override bool Equals(Object obj)
{ return base.Equals(obj) && z == ((Point3D) obj).z; }
public override int GetHashCode()
{ return base.GetHashCode() ^ z; }
} // end class Point3D
public class object1
{
public static void Main()
{
Point p1 = new Point(5,7);
Point p2 = new Point(6,8);
bool b1 = p1.Equals(p2);
Console.WriteLine("b1 = " + b1);
int h1 = p1.GetHashCode();
Console.WriteLine("h1 = " + h1);
Point3D p3 = new Point3D(5,6,9);
Point3D p4 = new Point3D(5,6,9);
bool b2 = p3.Equals(p4);
Console.WriteLine("b2 = " + b2);
int h2 = p3.GetHashCode();
Console.WriteLine("h2 = " + h2);
}
}
The method
protected object MemberwiseClone();
4.11. ENVIRONMENT CLASS 61
creates a shallow copy of the current object, i.e. it returns a shallow copy of the
current object. The following code shows how to copy an instance of a class using
Object.MemberwiseClone().
// object3.cs
using System;
class MyBaseClass
{
public static string CompanyName = "KXK";
public int age;
public string name;
}
class MyDerivedClass : MyBaseClass
{
public static void Main()
{
// create an instance of MyDerivedClass and assign values
// to its fields
MyDerivedClass m1 = new MyDerivedClass();
m1.age = 42;
m1.name = "John";
// performs a shallow copy of m1 and assign it to m2
MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone();
Console.WriteLine("age = " + m2.age);
Console.WriteLine("name = " + m2.name);
}
}
4.11 Environment Class
The Environment class provides information about, and means to manipulate, the
current environment and platform. The class is sealed, i.e. it cannot be inherited.
Version gets a Version object that describes the major, minor, build, and revision
numbers of the common language runtime. CommandLine provides the command line
for this process. CurrentDirectory provides the directory from which this process
starts. ExitCode gets or sets the exit code of the process. StackTrace provides current
stack trace information. SystemDirectory provides as string the fully qualified
path of the system directory. TickCount provides the number of milliseconds the
time passed since the system started. The method GetCommandLineArgs() returns
a string array containing the command line arguments of the current process. The
62 CHAPTER 4. BUILT-IN CLASSES
method Exit() terminates this process and gives the underlying operating system
the specified exit code. The class also contain the methods ToString and Equals.
// enviro.cs
using System;
class MyEnviro
{
public static void Main()
{
object ver = Environment.Version;
Console.WriteLine("ver = " + ver); // 2.0.50727.312
string com = Environment.CommandLine;
Console.WriteLine("com = " + com); // enviro
string cd = Environment.CurrentDirectory;
Console.WriteLine("cd = " + cd); // C:\csharp
int ex = Environment.ExitCode;
Console.WriteLine("ex = " + ex); // 0
string st = Environment.StackTrace;
Console.WriteLine("st = " + st); // at System.Environment ....
... at MyEnviro.Main()
string sd = Environment.SystemDirectory;
Console.WriteLine("sd = " + sd); // C:\Windows\System32
int t = Environment.TickCount;
Console.WriteLine("t = " + t); // 300223
string[] comline = Environment.GetCommandLineArgs();
Console.WriteLine("comline = " + comline); // System.String[]
int i = 7;
int x = 15/2;
if(x==i) Environment.Exit(0); // true
Console.WriteLine("did we reach this point?");
}
}
No comments:
Post a Comment