Before getting into classes, we will look at memory storage first. Data in C# is stored in a variable in one of two ways, depending on the type of variable. There are reference variables and value variables. Value types store themselves and their content in one place in memory. Reference types hold their name and a pointer to some other place in memory where their content is held. That other place is called the heap.
An int (integer) is a value type. Strings are reference types. When declaring these variables in C# you don’t have to do anything special. Its done for you. Value types always contain a value but reference types can be null. It is possible to create a value type that can contain null by using nullable types. Generic types is a topic that includes nullable types.
The only simple types that are reference types are string and object, although arrays are implicitly reference types as well. Every class you create will be a reference type.
When you declare a variable of type integer, all you need to do is specify the type and the identifier. The type will be int and the identifier is the name you give to the integer. For example, look at the code below. The first line of code creates the variable int and allocates memory for it. The second line assigns the value 7 to the variable.
int myInt; myInt = 7;
Classes Instantiate with New
Now let’s look at classes. Suppose we have a class that we want to create called Person. We start with the type (Person) and an identifier (person). However, memory is not yet allocated. We need to use the new operator. In C# classes are treated differently than primitive types. You have allocated memory here, but you don’t have to worry about unallocating it Why? The CLR does this work for you. It is called garbage collection.
Person person = new Person(); // we can shorten the code with the var keyword like so: var person = new Person();
Once we have defined a class and instantiated the object with the new keyword, we can access the object’s members.
person.Name = "Mike"; // Name is a property (similar to primitive type string) person.Talk(); // Talk is a method (similar to a function)
Two Parts: Data and Behaviour
A class essentially has two parts: data and behaviour. Data is contained in fields, and behaviour is expressed in methods. You can see in the UML diagram below for a Customer class that there are four data parts and two method parts.
UML – Unified Modelling Language
UML (Unified Modeling Language) is a standard language for specifying, visualizing, constructing, and documenting the artifacts of software systems. UML was created by the Object Management Group (OMG) and UML 1.0 specification draft was proposed to the OMG in January 1997.