Object-oriented Programming with C#


class Employee {
// -- Attributes
//
public int EmployeeID;
public string Name;
public bool Married;
public int Status;
public decimal Salary;

// -- Functions
//
public decimal Tax() {
decimal calcTax;
// Assume tax is at 20%
calcTax = Salary * ((decimal)0.2);
return (calcTax);
}
}

class Example {
static void Main() {
Employee Jeff = new Employee();
Jeff.Salary = 10000;
System.Console.WriteLine("Jeff's tax of {0} is too much!\n",Jeff.Tax());
}
}

The last concept is inheritance. Inheritance is the foundation and fundamental support for object-orientation. It allows a class to "inherit" the characteristics and attributes of the parent class. Visual Basic does not support inheritance and hence cannot really qualify as an object-oriented language. In the new version Visual Basic, VB.Net, inheritance is now part of the VB language.

The following is an example of inheritance in C#.

Listing 4
class mammal {
public int eyes;
public int legs;
}

class Human : mammal {
// -- Constructors
// --
public Human() {
eyes = 2;
legs = 2;
}

public void ShowAttr() {
System.Console.WriteLine("Humans have {0} eyes and {1} legs.",eyes, legs);
}
}

class Dog : mammal {
// -- Constructors
// --
public Dog() {
eyes = 2;
legs = 4;
}

public void ShowAttr() {
System.Console.WriteLine("Dogs have {0} eyes and {1} legs.",eyes, legs);
}
}

class Example {
static void Main() {
Human Jeff = new Human();
Dog Biff = new Dog();

Biff.ShowAttr();
Jeff.ShowAttr();
}
}

Listing 4 introduces another concept called constructors. In C# a constructor is part of a class that has the same name. You can have multiple constructors in C# as long as they have different parameters, or signatures. Similar to C++, constructors are called first when an object is instantiated.

While on the topic of inheritance, C++ allows you to inherit from multiple classes. This presents a problem when two classes have a method with the same signature. C# does not allow multiple inheritance.

Another problem that C# tries to address is the abuse of a class. C# has a sealed class qualifier, which prevents other classes to create accidental inheritance. For example, it is not possible to inherit the String object. The advantage of doing this is to have a consistent and common view of strings. Remember, .Net was designed to increase re-usable code. Therefore, objects such as the String object is shared with other programming languages such as Visual Basic, which handles strings

The copyright of the article Object-oriented Programming with C# in C# Programming is owned by Jose Aniceto. Permission to republish Object-oriented Programming with C# in print or online must be granted by the author in writing.

Go To Page: 1 2 3

Articles in this Topic    Discussions in this Topic