Overriding Methods in C#

In addition to producing a new class based on an old one by adding additional features, you can modify existing behavior of the parent class.

If a method is defined in a derived class so that the name, return type, and argument list match exactly those of a method in the parent class, then the new method is said to override the old one.

The keyword virtual

In C#, a class can declare virtual methods, properties, and indexers, and derived classes can override the implementation of these function members.

The keyword virtual allows programmers to specify methods that a derived class can override, C# methods are non-virtual by default and must be explicitly declared as virtual.

The implementation of a non-virtual method is invariant: The implementation is the same whether the method is invoked on an instance of the class in which it is declared or an instance of derived class. In contrast, the implementation of a virtual method can be changed by derived classes.

The keyword override

To override a base-class method definition, a derived class must specify that the derived-class method overrides the base-class method with keyword override in the method header.

If the override modifier is not used, the new member hides the inherited member, and a compiler warning occurs. If a derived class attempts to override a non-virtual inherited member, a compiler error will occur.
The following examples illustrate the using of virtual and override keywords.

Fig 1. Class diagram for Employee and Manager using Inheritance.

Listing 1: Sample code for Employee class

Listing 2: Sample code for Manager class

Consider these sample methods in the Employee and Manager classes:
Fig 2. The GetDetails method of the Employee class.

Fig 3. The GetDetails method of the Manager class.

The Manager class has a GetDetails method by definition because it inherits one from the Employee class. However, the original method has been replaced, or overridden, by the derived class’s version.

Listing 3 A simple program to demonstrate how method overriding works.

Fig 4 The output of executing this program is the following.

Download the source code.

Understanding abstract classes with C#

The C# programming language enables a class designer to specify that a base class declares a method that does not supply an implementation. This is called an abstract method. The implementation of this method is supplied by the derived classes. Any class with one or more abstract method is called an abstract class.

Fig 1 UML model of the abstract class.

The purpose of an abstract class is primarily to provide an appropriate base class from which other classes can inherit and thus share a common design.
However, abstract classes can have data attributes, concrete methods, and constructors. For example, the Vehicle class might include load and maxLoad attributes and a constructor to initialize them.
Not all inheritance hierarchies contain abstract classes. However, programmers often write client code that uses only abstract base class types to reduce the client code’s dependencies on a range of specific derived class types.
The C# compiler always prevents you form instantiating an abstract class, for example the following statement is illegal.

 Vehicle v = new Vehicle(); // this is illegal and the compiler generates an error.

Although we cannot instantiate objects of abstract base classes, we will see that we can use abstract base classes to declare variables that can hold references to objects of any concrete classes derived from those abstract classes.

The employee abstract class: A example using Polymorphism through inheritance

What is polymorphism?

The term polymorphism refers to the ability of two or more objects belonging to different classes to respond to exactly the same message (method call) in different class-specific ways, thus polymorphism enables us to “program in the general” rather than “program in the specific”.

Polymorphism allows:

  • Different behavoirs from the same type.
  • Runtime polymorphism is done via overriding.
  • Compile time polymorphism is done via method overloading.
  • Invoke methods of a derived class through a base class.

I think the best way to learn about this concept is through an example, so I wrote a set of examples using an inheritance hierarchy containing types of employees in a company.

Fig 2 Employee hierarchy UML class diagram.

We use abstract class Employee to represent the general concept of an employee. The classes that inherit from Employee are: CommissionEmployee, PieceEmployee and HourlyEmployee.

1. I use abstract class Employee to represent the general concept of an employee. The classes that inherit from Employee are: CommissionEmployee, PieceEmployee and HourlyEmployee.

Listing 1. Abstract base class Employee

In this example, class Employee will provide two methods Earnings and Details, and properties that manipulate an Employee’s instance variables, the method Earnings certainly applies generally to all employee’s, but each earnings calculation depends on the derived employee’s class. So these two methods must be abstract in the Employee class because an implementation does not make sense there, so each derived class must override those methods with an appropriate implementation.

2. I wrote three concrete classes: HourlyWorker, CommissionWorker and PieceWorker. Such classes provide implementations of the abstracts methods declared in our abstract class, because abstract base classes are too general to create real objects.

Listing 2. Concrete derived class HourlyEmployee

Listing 3. Concrete derived class CommissionEmployee

Listing 4. Concrete derived class PieceWorker

To test our example, the following program creates an array of our abstract base class Employee, then assigns the four instances of our concretes classes to the array variable. Finally, the program iterates through array Employee and polymorphically invokes methods Earnings and Details to display the output of each of these methods.

Listing 5. Test program for our example.

Fig 3. The output for our example.

Note: Those examples were based on the examples included in: Deitel’s developer series C# 2010 for programmers.

Download the source code.

Understanding Bitwise Logical Operators with C#

Bit manipulation operations, including logical and shift operations, perform low-level operations directly on the binary representations used in integers. The ability to operate directly on binary might save large amounts of memory, might enable certain computations to be performed very efficiently, and can greatly simplify operations on collections of bits, such as data read form or written to parallel I/O ports.

The C# programming language supports bitwise operations on both numeric and boolean data types. These are represented as the operators ~, &, ^, and | for the bitwise operations of NOT (bitwise complement), bitwise AND, bitwise XOR, and bitwise OR, respectively.
The operators work in parallel on all bits of the operands and never cause overflow, even in a checked context.

Unsigned integers are normally used with the bitwise operators.

Bitwise NOT (complement)

The bitwise complement or NOT is used to flip the bits of a value, this operator is unary and inverts the bit value. Since this operator is a unary operator it cannot be combined with the = sign.

Fig 1 Example of bitwise NOT operator

Bitwise XOR

When combining two values with the logical XOR bitwise operator, you get the following result: if both bits are the same, the result is 0 else if 1 bit is 0 and the other is 1, the result is 1

Fig 2 Example of bitwise XOR Operator

Bitwise OR

When combining 2 byte values results in the following: if both bits are 0, the result is 0. If either or both bits are 1, the result is 1.

Fig 3 Example of bitwise OR operator

Bitwise AND

The bitwise AND operator produces a one in the output bit if both input bits are one; otherwise it produces a zero.

Fig 4 Example of bitwise AND operator

When using the bitwise operator, it’s useful to display values in binary to show the precise effects of these operators.
The following example demonstrate the use of the bitwise operators, it uses the method PrintBits (implemented in class Util) to print the unsigned int values.

The full sample is shown below:

Listing 1 Source code for Util class

Listing 2 Source code for the main program class

Fig 5 Running the sample

Fig 6 Output of the complete example

Download source code

Understanding Interfaces with C#

The public interface of a class is a contract between the client code and the class that provides the service. Concrete classes implement each method. However, an abstract class can defer the implementation by declaring the method to be abstract, and a C# interface declares only the contract and no implementation.

A concrete class implements an interface by defining all methods declared by the interface. Many classes can implement the same interface. These classes do not need to share the same class hierarchy. Also, a class can implements more than one interface.

Imagine a group of objects that all share the same ability: they fly. You can construct a public interface, called Flyer, that supports three operations: TakeOff, Land and Fly.

Fig 1. The interface flyer and airplane class diagram

Listing 1 The Flyer code

Listing 2 The Airplane code

There can be multiple classes that implement the Flyer interface, as shown of the next figure

Fig 2. Multiple implementations of the Flyer interface.

This sounds like multiple inheritance, but it is not quite that. The danger of multiple inheritance is that a class could inherit two distinct implementation of the same method.

Fig 3. A mixture of inheritance and implementation.

An Airplane is a Vehicle, and it can fly. A bird is an Animal, and it can fly. These examples show that a class can inherit from one class but also implement some other interface.

This sounds like multiple inheritance, but it is not quite that. The confusion of multiple inheritance is that a class could inherit two distinct implementations of the same method. This is not possible with interfaces because an interface method declaration does not supply implementation.
Suppose that you are constructing an aircraft control software system. The following diagram shows its class hierarchy

Fig 4. A mixture of inheritance and implementation.

The airport must grant permission to land and take off for flying objects of all types, then the code for the airport could look like the following.

Listing 3 The code for granting permission

Fig 5. Running the sample

Download source code

C# Recipe 1: How to calculate a leap year.

The Gregorian Calendar is the most widely used calendar in the world today.It is a reform of the Julian calendar, proposed by Aloysius Lilius, and decreed by Pope Gregory XIII, from whom it was named, on 24 February 1582 by papal bull Inter gravissimas

The changes made by Gregory also corrected the drift in the civil calendar which arose because the mean Julian calendar year was slightly too long, causing the vernal equinox, and consequently the date on which Easter was being celebrated, to slowly drift forward in relation to the civil calendar and the seasons. The Gregorian Calendar system dealt with these problems by dropping 10 days to bring the calendar back into synchronization with the seasons, and adopting the following leap year rule:

Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1800 is not a leap year; the year 1984 is a leap year and the year 2000 too.

Fig 1 The following example calculates a leap year.



Fig 2 Running the sample, output 1



Fig 3 Running the sample, output 2



Download source code

Algoritmo Genético para el TSP (Traveling Salesman Problem) con Monodevelop utilizando C#

La computación evolutiva es una parte de la inteligencia artificial donde se agrupan diferentes técnicas adaptativas enfocadas a encontrar las mejores soluciones para resolver problemas de optimización, estas técnicas parten de una de las principales ideas que existen en la teoría de la evolución biológica propuesta por Charles Darwin, la selección natural es el proceso histórico de transformación de unas especies en otras especies descendientes e incluye la extinción de la gran mayoría de las especies que han existido, lo que es sin duda un problema de optimización además de que muchos de los términos que utiliza la computación evolutiva son tomados de la biología, con la advertencia de que se son usados para representar más o menos la misma idea biológica lo que no equivale a que sean iguales.

La computación evolutiva se compone por las siguientes técnicas:

  1. Programación evolutiva: Son una estrategia de optimización estocástica hacen un énfasis específico en los operadores genéticos tal y como se observan en la naturaleza.
  2. Estrategias evolutivas: Esta técnica esta básicamente enfocada hacia la optimización. En esencia son métodos estocásticos con paso adaptativo, que permiten resolver problemas. A este método se le han agregado procedimientos propios de la computación evolutiva, que lo han convertido en un paradigma más de dicha metodología.
  3. Algoritmos genéticos: Usan métodos que tienen analogía en la selección natural y la evolución.

Entre los usos de la computación evolutiva se encuentran la planificación, el diseño de sistemas, la simulación, el reconocimiento de patrones, el control y la clasificación de datos.

La alternativa para una solución de problemas de planificación y de optimización donde la mayoría están se ubican dentro de la categoría de los problemas NP los cuales no pueden ser resueltos usando las técnicas convencionales y solo pueden ser atacados desde las técnicas de computación evolutiva donde el dominio de esos problemas le corresponden a los algoritmos genéticos (John H. Holland, 1975) 

Como ejemplo de este tipo de aplicaciones me encontré en este web site (http://www.heatonresearch.com) un Applet Java, que utiliza algoritmos genéticos para obtener una solución optima al problema del agente viajero (Traveling Salesman Problem), en el mismo web site el autor nos hace un resumen del problema.

Pues bien como un ejercicio de aprendizaje, traduje el código del applet de Java a C# como un proyecto de Monodevelop utilizando Winforms, a continuación algunas screenshots y el código fuente del proyecto. He de aclarar que debido a la falta de tiempo hice casi copia tal cuál del código, modificando las partes de Java que el compilador me marcaba como errores.

Inicio de la aplicación

Aplicación en ejecucción

Resultado de la aplicación

En su web site el autor Jeff Heaton además del código fuente del applet, ofrece libros acerca de inteligencia artificial y de programación con Java y C#.

Descarga el código fuente en un proyecto para MonoDevelop o Visual Studio