Defining and Using a Class On C#

by Administrator 18. May 2009 14:16

In C#, you use the class keyword to define a new class. The data and methods of the class oc-
cur in the body of the class between a pair of braces. Here is a C# class called Circle that con-
tains one method (to calculate the circle’s area) and one piece of data (the circle’s radius):

class Circle
{
    double Area()
    {
        return Math.PI * radius * radius;
    }
    int radius;
}

The body of a class contains ordinary methods (such as Area) and fields (such as radius)—
remember that variables in a class are called fields. You’ve already seen how to declare vari-
ables in Chapter 2, “Working with Variables, Operators, and Expressions,” and how to write
methods in Chapter 3, “Writing Methods and Applying Scope”; in fact, there’s almost no new
syntax here.
Using the Circle class is similar to using other types that you have already met; you create a
variable specifying Circle as its type, and then you initialize the variable with some valid data.
Here is an example:

Circle c;           // Create a Circle variable
c = new Circle();   // Initialize it

Note the use of the new keyword. Previously, when you initialized a variable such as an int or
a float, you simply assigned it a value:

int i;
i = 42;

You cannot do the same with variables of class types. One reason is that C# just doesn’t pro-
vide the syntax for assigning literal class values to variables

Another reason concerns the way in which memory for variables of class types is al-
located and managed by the runtime

 

Tags:

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

 

My Quote :P

Each morning when I open my eyes I say to myself: I, not events, have the power to make me happy or unhappy today. I can choose which it shall be. Yesterday is dead, tomorrow hasn’t arrived yet. I have just one day, today, and I’m going to be happy in it.

Month List

Page List