Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of base() in C#

Tags:

c#

constructor

I've been learning C# and wanted to review some open source projects to see some good written code. I found a project called Todomoo on sourceforge and there's a part that is puzzling me:

public class Category {

    // Note properties
    private int id = 0;
    private string name = "";
    private Color colour = Color.Gray;

    /// <summary>
    /// Create a new category.
    /// </summary>
    public Category() { }

    /// <summary>
    /// Load a category from the database.
    /// </summary>
    /// <param name="Id">ID of the category</param>
    public Category(int id) : base() {
        Load(id);
    }

Here it uses base() in one of the constructors, but the class is not a derived class. So what exactly is that for?

And why is the syntax of base() is that way and not like:

    public Category(int id) {
        base();
        Load(id);
    }
like image 917
hattenn Avatar asked Aug 08 '12 14:08

hattenn


People also ask

What is difference between this () and base () in C#?

this refers to the current class instance. base refers to the base class of the current instance, that is, the class from which it is derived.

What is the purpose of a base class?

A base class is a class, in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).

What is base constructor?

The constructor of a base class used to instantiate the objects of the base class and the constructor of the derived class used to instantiate the object of the derived class.

What is base type in C#?

The base type is the type from which the current type directly inherits. Object is the only type that does not have a base type, therefore null is returned as the base type of Object. Interfaces inherit from zero or more base interfaces; therefore, this property returns null if the Type object represents an interface.


1 Answers

but the class is not a derived class

The class is a derived class - it implicitly inherits from System.Object. It is not clear why anyone would invoke base() constructor for System.Object, though: it is done implicitly as well.

As far as the syntax goes, my guess is that C# adopted a syntax that is close to C++ initializer lists, not to Java invocation of base constructors.

like image 118
Sergey Kalinichenko Avatar answered Oct 06 '22 01:10

Sergey Kalinichenko