Search code examples
c#programming-languagestheory

What is a class?


I can imagine the first reaction when you read the title of my question: "How can you have such a high reputation here and ignore what a class is?"

My point is the following: until now I have always worked with C++, Delphi, Java, ... and there it's quite simple: a class is a type definition of an object. You need to reserve some space in memory to start using it (hence the constructor) and afterwards, don't forget to free that memory (if your programming language does not support garbage collection).

Today, however, I had a problem concerning type definitions and constants in C#, and I fell on this URL, mentioning such pieces of source code:

class Calendar1
{
  public const int Months = 12;
}

In order to use this, you just need to do:

using Calendar1;

And you can use Months as a constant.

But here's my question: where's the constructor? If this class is the type definition of an object, which object are we talking about?

So, if I understand correctly, C# is based on the idea "Everything is a class", but in order to make this work, the C# inventors have extended the definition of a class, so now we get (C# definition):

A class is one of the following:

  • a type definition for an object. In that case, a constructor is needed for creating the object.
  • ...

Can somebody finish the definition?


Solution

  • This is a pretty common practice in C#. Classes are often used to create "sacks" to hold constants, or commonly as a entity or dto object. These are usually made without a user defined constructor. If a class does not have a constructor, one is defined at compile time which amounts to an empty constructor:

    public Calendar1()
    {
    }
    

    This answer goes into much further detail: C# class without constructor