Click here to Skip to main content
Click here to Skip to main content

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

, 7 Jul 2011
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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:

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:

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:

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:

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:

public void ModifyMonths()
{
    months = 4;
}

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

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:

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:

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)

About the Author

Morteza Giti
Student
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
I live in Shiraz,Iran-the kingdom of Cyrus, The Great. I'm a university student and I'm studying software engineering at the moment. I began programming when I was around fifteen. having started my journey with VB6, I moved to VB.NET after two years and one year later I turned my face to C# as I found it more interesting and challenging. These days, I'm learning WPF and Silverlight. I also like MVC.

Comments and Discussions

 
QuestionMy vote of 4 PinmemberSaadmaan Mahmid13-May-14 20:55 
GeneralMy vote of 3 Pinmemberafaz12-Jul-11 1:18 
Questiondecent PinmemberCIDev8-Jul-11 3:19 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 7 Jul 2011
Article Copyright 2011 by Morteza Giti
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid