C# class can be used to create objects. Classes are the cornerstone of object orientated programming (oop).

A c# program can have multiple objects. An object is essentially a collection of methods and variables. Each object has its own values, but the methods and variable names derrive from the class definition.

Classes in C#

Class example

This concept can be challenging to grasp, and is easier to understand with an example.
The c# program below creates an object from the defined class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

namespace CubeApplication {
class Cube {
public double length;

public void showSize( ) {
Console.WriteLine("Cube is {0}x{0},{0}", this.length);
}
}

class Boxtester {
static void Main(string[] args) {
Cube c1 = new Cube();
Cube c2 = new Cube();

c1.length = 3;
c2.length = 4;

c1.showSize();
c2.showSize();

Console.ReadKey();
}
}
}

The above program defines a class (cube) which has a property and a method. Then two objects are created.

The attributes of the objects are set, and shown using the class method.
The output should be similar to:

1
2
Cube is 3x3x3
Cube is 4x4x4

Exercises

  1. Create two objects from a class.
  2. Can an object create a class?