Conteúdo do Curso
C# Beyond Basics
C# Beyond Basics
The `static` Keyword
index
It was a convenient way to describe the static
keyword at that time because it was expected that the reader might not have any knowledge of objects or classes at that point, however now if you look at the code, you might realize that val
is basically a field of the ConsoleApp
class. However, note that the ConsoleApp
class is slightly different from the classes we normally create. It is because ConsoleApp
represents the program itself, and there is no object of the ConsoleApp
. We will get back to this part in a bit.
Since a class is only a blueprint, more like a hollow shell, it does not normally contain data by itself, instead we create objects using that blueprint and then store and access data from those objects - as explained before:
index
Even inside a class, when we are accessing those fields, we are accessing them through an object. For-example in a constructor, we are basically using the data that was passed by the object which called the constructor method:
index
Similarly, in other methods as well, when we are accessing fields, we are basically accessing the fields of objects which call those methods, and not of the class itself because class normally does not contain any data.
However, there is a way to store data into a class directly and make a property accessible without needing to create an object. We can do that by simply making that field or method static
:
index
Since the ConsoleApp
or the main class of any program which represents the program itself cannot have any objects, we need to make their methods and fields static. This is why the Main
method is static
as well:
index
Tudo estava claro?