Introduction to Objects and Classes in C# - Creating Objects and Classes
(Page 8 of 9 )
We create a class by defining it using the keyword class followed by the class name:
class Person
Then we open a left brace "{" and write our methods and properties. We then close it with a right brace "}". That's how we create a class. Let's see how we create an instance of that class.
In the same way as we declare a variable of type int we create an object variable of Person type with some modifications:
int age;
Person Michael = new Person();
In the first line of code we specified integer variable called age. In the second line we first specified the type of Object we need to create, followed by the object's name, followed by a reserved operator called new. We end by typing the class name again followed by parentheses "()".
Let's understand it step-by-step. Specifying the class name at the beginning tells the C# Compiler to allocate a memory location for that type (the C# compiler knows all the variables and properties and methods of the class so it will allocate the right amount of memory). Then we followed the class name by our object variable name that we want it to go by. The rest of the code "= new Person();" calls the object's constructor. We will talk about constructors later but for now understand that the constructor is a way to initialize your object's variable while you are. For example, the Michael object we created in the last section can be written as following :
Person Michael = new Person(20, "Brown");
Here I specified the variable's values in the parameter list so I initialized the variables while creating the object. But for this code to work we will need to specify the constructor in the Person class -- I will not do that yet as constructors will come in a later article.
Next: Conclusion >>
More C# Articles
More By Michael Youssef