Object Oriented Programming using C#

(backadmin) #1

Object Oriented Programming using C#
Generic Collections and how to Serialize them


We could even define a version of this method to find the highest student (alphabetically).


static public Student Highest(Student o1, Student o2)
{
if (o1.ToString().CompareTo(o2.ToString()) > 0)
return o1;
else
return o2;
}

And invoke this using ..


Student s1 = new Student(“Alan”);
Student s2 = new Student(“Clare”);
Console.WriteLine(“The highest is “ + Highest(s1, s2));

In doing this we have created three methods that essentially do exactly the same thing only using different parameter
types. This leads us to the idea that it would be nice to create just one method that would work with objects of any type.


The method below is a first attempt to do this :-


static public Object Highest(Object o1, Object o2)
{
if (o1.ToString().CompareTo(o2.ToString()) > 0)
return o1;
else
return o2;
}

This method takes any two ‘Objects’ as parameters. ‘Object’ is the base class of all other classes thus this method can take
any two objects of any more specific type and treat these as of the base type ‘Object’. This is polymorphism.


The method above then converts these two ‘Object’s to strings and compares these strings.


Thus this one method can be invoked three times using the following code....


int n1 = 1;
int n2 = 2;
Console.WriteLine(“The highest is “ + Highest(n1, n2));
double n3 = 1.1;
double n4 = 2.2;
Console.WriteLine(“The highest is “ + Highest(n3, n4));
Student s1 = new Student(“Student A”);
Student s2 = new Student(“Student B”);
Console.WriteLine(“The highest is “ + Highest(s1, s2));
Free download pdf