1.2 Creating a class
- Start Visual Studio and create a new project.
- Choose a folder where you will place all your Visual Studio projects. Name the project
Geometry. - Make sure the Solution Explorer is visible on the left side.
- Create a
Modelsfolder under the project. From now on, we will place all classes that define objects together in this folder. - Make sure the
Modelsfolder is selected. - Create a new C# class and name it
Circle. -
You will now see the following:
1 2 3 4 5 6
namespace Geometry.Models { public class Circle { } }You can see both the namespace name and the class name here.
We first specify the attributes. A circle has a center point with an x-coordinate and a y-coordinate, and a circle has a radius. A circle also gets a color.
-
Make sure you have the following on your screen:
1 2 3 4 5 6 7 8 9 10
namespace Geometry.Models { public class Circle { public double Radius; public double CenterX; public double CenterY; public string Color; } }This means that every object of the
Circleclass has three attributes of typedoubleand one attribute of typestring.If the radius of a circle is known, then the circle itself can calculate the perimeter and the area. Below is how that works.
-
Add the two methods according to the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
namespace Geometry.Models { public class Circle { public double Radius; public double CenterX; public double CenterY; public string Color; public double CalculatePerimeter() { return 2 * Math.PI * Radius; } public double CalculateArea() { return Math.PI * Radius * Radius; } } }The perimeter of a circle is 2π * radius and the area of a circle is π(radius)². Both methods return the result as a value of type
double.We use UML class diagrams for an overview of the class. The class diagram of the
Circleclass looks like this:The top cell contains the name of the namespace (Models) and the name of the class (Circle), separated by two colons.
The second cell contains the attributes (Radius, CenterX, CenterY, and Color). The plus sign means that the attribute is public (visible everywhere and therefore available). Next, you see the name of the attribute and its type.
The third cell contains the methods (CalculatePerimeter and CalculateArea). The plus sign again means that the method is public. Next, you see the name of the method and after the colon the return type.