C #: from medium to advance level [Classes and Constructors (Part I)]

Matteo Lo Piccolo
3 min readAug 9, 2021

Ok, we talked about classes in the past articles, but now I go deep in this important topic.
To declare a Class in C# we use this syntax

public class Person

we start with the ACCESS MODIFIER, and it can be public, private, protected or internal.
Don’t worry, we will see everything of these topic in these articles.
Then the keyword “class” and the name of it.
The name is always in Pascal Case.

Every classes can have fields and methos

Declare fields is exactly like declare class.
We have access modifier, the type of fields (int, string, bool, etc…) and the name.

And same for methods

public void Introduce

Methods can be VOID (it means don’t return nothing) or of some type, like int, bool, or Array, List, etc.

Now, to “use” these objects, we need to create them.
To do that, we use the “new” keyword

You can use Person or var, the result is the same.
Honestly I always use “var” keywords, I don’t know if it is better or not.

Don’t worry about red underline, it is because I give same name to the variables, and we cannot do that.

When we create an object, we need the type, so name of the Class or var, and a name in camel case, then equal sign, “new” keyword and again the name of the class.
It means we have create a new instantiation of the Class.

After we create a Class object, we can access to the fields or methods like this

Before advance, we talk about INSTANCE members, and STATIC members.
The basic difference is this : we can access to the instance members from the OBJECT, instead we can access to the static members DIRECTLY FROM THE CLASS.

A classic example of static method is this

We can access to the method WriteLine DIRECTLY from the Console class, we don’t have to create a new object Console every time.

The question is : why we have to use the “static” keyword?
Well, experience helps a lot, but : normally we use “static” when we have concept that are SINGLETON.
It means we have only one instance of that object in memory.

Two examples are DateTime.Now or Console.WriteLine()
We have one place in memory that represent the concept of DateTime.Now, we don’t need to create many object for that.
In the Console case, we need only one Console in our program, that’s why is static.

To declare something static, we simply use the “static” keyword like this

--

--

Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!