Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#
Article

Object-Oriented Programming in C# .NET - Part 3

Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
7 Jul 2011CPOL5 min read 36K   23   3
A discussion of constructors, finalizers, static classes and static members, constants and abstract classes in C#

Introduction

Without any unnecessary introduction, I will start discussion of part three of this series. If you haven’t studied the previous parts of this article, I highly recommend that you do so now. For studying part one click here, and for studying part two click here.

In this part, we will talk about the following:

  • Constructors
  • Finalizers
  • Static classes and static members
  • Constants
  • Abstract classes

What is a Constructor?

A constructor is simply a method within a class with an interesting characteristic. A constructor’s name is the same as the name of the class in which it’s declared. A constructor is the method that’s called whenever you use the new keyword to instantiate a class. A class may have none, one or many constructors. If you don’t declare a constructor within a class, C# adds a parameterless, default constructor for you. However, if you add your custom constructor, the default one will be gone. You can do anything you want in a constructor’s body; setting default values for properties and values, etc. Take a look at the following example:

C#
class Car
{
    public Car()
    {   
        Name = "NoName";
        NumberOfDoors = 4;
    }
    private string Name;
        
    public void PrintName()
    {
        Console.WriteLine (Name);
    }
        
        //…other lines of code omitted here…
    }

As you see, we have set the value of Name and NumberOfDoors to two default values. However, we can also set them to values that the user of our Car class provides. Look at the following constructor:

C#
public Car(string name, int numberOfDoors)
{
    Name = name;
    NumberOfDoors = numberOfDoors ;
}

This constructor has two parameters. (Remember I said that constructors are merely methods and methods can have parameters and also return types. Unlike ordinary methods, though, a constructor doesn’t have a return.) We set the values of Name and NumberOfDoors to the values that the user provides when calling the constructor:

C#
class Program
{
    static void Main(string[] args)
    {
        Car c = new Car ( "My Car", 4 );     
    }
}

What is a Finalizer?

As the name implies, a Finalizer is the method that is called when an instance of a class leaves is destroyed and leaves the memory. A class may have one and only one Finalizer. Finalizers cannot be invoked; they are called automatically. A Finalizer cannot have any parameters or access modifiers. The syntax for creating a Finalizer is the same as the constructor except the fact that a ~ is added to the beginning of the Finalizer. Take a look at the following example:

C#
class Car
{
    ~Car()
    {
        Console.WriteLine (Name);
    }
}

Whenever an object of type car is going to be cleaned from the memory, it writes out the Name property to the console. You can do cleanup jobs in a Finalizer. Of course, there are many hints and notes on this subject, but as I said at the beginning I don’t intend to go through all of them.

What is a Static Class and a Static Member?

Static classes are a kind of class. However, there are some differences between static and non-static classes. A static class cannot be instantiated, which means you cannot declare a variable of type static class using the new keyword. A static class may only have static members but not non-static members. A static class is accessed via the name of the class itself rather than an object of that type. For example, take a look at the following class called Math:

C#
static class Math
{
    public static double Add(double x, double y)
    {
        return x + y;
    }
}

This class is declared static and has a method which is, as well, static. Now, if we want to call method Add, we access it via the name of the Math class rather than declaring an object of Math class first and then accessing Add via that object:

C#
class Program
{
    static void Main(string[] args)
    {
        double result = Math.Add ( 3.2, 1.4 );
        Console.WriteLine (result );
        Console.ReadKey ();        
    }
}

What is a Constant?

A constant is a value that is, well, constant during the life of an application or, in our case, an object of your class. Only C# built-in types can be declared as constant. For declaring objects not included in C# built-in types, we take advantage of the readonly keyword and set the value of that read-only item in, for example, the class’s constructor. A constant’s value must be set at the point of declaration and cannot be changed afterwards. A constant can have any of the access modifiers. We declare a member as constant by adding the const keyword before it. Suppose we declare a Calendar class. Take a look at the following example:

C#
class Calendar
{
    public const int months = 12;
    private  const int weeks = 52;
    protected const int days = 365;
 
    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}

Afterwards, if we try to modify the values stored in these constants, we will encounter an error:

C#
public void ModifyMonths()
{
    months = 4;
}

Even if we try to associate a property with a constant, we will, again, encounter an error:

C#
int Month
{
    get { return months; }
    set { months = value; }
}

The way to access constants is quite like the way we access static members. Since, a constant’s value is the same for all of the instances of a class, it’s treated like a static member. You don’t have to mark a constant field as static:

C#
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine (Calendar.months );
        Console.ReadKey ();
    }
}

What is an Abstract Class?

An abstract class is a special kind of class. An abstract class cannot be instantiated. So, if we cannot declare a type of an abstract class, what is the point in creating an abstract class? Abstract classes are used in inheritance and when we cover the concept of inheritance in the next part of this article, you will find the benefit. For now, just keep in mind that an abstract class provides incomplete members for the derived classes to override. An abstract class may have abstract members. We make an abstract class by putting the abstract keyword before the name of the class:

C#
abstract class Draw
{
    public abstract void DrawIt();
    public int someValue = 3;
    public int SomeValue
    {
        get { return someValue; }
        set { someValue = value; }
    }
}

The method named DrawIt is marked as abstract and must be implemented by classes that derive from Draw class. Note that the DrawIt method has no body and the body is to be created in the derived classes. However, someValue is not abstract and doesn’t need to be implemented by derived classes. Any derived class can have direct access to SomeValue property as it’s marked as public.

I think that’s enough for the part three of this article. Stay tuned for part four. Good luck!

History

  • 5th July, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
I'm a software engineer specialized in .NET framework. I've developed applications in such technologies as Console Applications, Windows Forms, WPF, Web Forms, MVC, Silverlight and Xamarin Forms. I also create and publish my multimedia courses at provid.ir and softdevwithmorteza.wordpress.com.
Some of my courses inclue Design Patterns in C#, OOP Principles, SOLID Principles, High Quality Coding Principles, Anti-patterns, Refactoring, TDD, DDD, .NET Core and so on.

Comments and Discussions

 
QuestionMy vote of 4 Pin
Saadmaan Mahmid13-May-14 20:55
Saadmaan Mahmid13-May-14 20:55 
-
GeneralMy vote of 3 Pin
Abolfazl Khusniddinov12-Jul-11 1:18
Abolfazl Khusniddinov12-Jul-11 1:18 
Questiondecent Pin
BillW338-Jul-11 3:19
professionalBillW338-Jul-11 3:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.