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);
}
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With