C# Simplified - Classes
(Page 5 of 5 )
Classes are the fundamental concept in an Object Oriented Programming Language such as C#. It would be more appropriate to discuss the meaning of a class with reference to an object. This is because these two words are interrelated. While a class is a combination of related objects, an object is an instance of the respective class. Actually, .NET Framework itself provides us with lot of classes with which you can perform a wide variety of tasks. But before applying these classes in a C# program, you have to define your own class. It is defined as shown below:
Listing 1.7
class Computer
{
// Declarations goes here
}
The opening and closing curly braces are important while declaring a class. It is in between these braces you declare variables, Main() method and also perform lot of other tasks.
Creating an instance of a class
After declaring a class you can create an instance of it by using the new keyword. The general syntax for creating an instance of a class is shown below:
Listing 1.8
YourClassname Yourobjectname = new Constructor();
Hence, for a class named Computer the declaration should be as in listing 1.9
Listing 1.9
Computer comp = new Computer();
To access a variable using the above object name, you should use the dot operator as shown in listing 1.10:
Listing 1.10
using System;
class VarAccess
{
int x = 1000;
int y = 2000;
public static void Main()
{
VarAccess va = new VarAccess();
Console.WriteLine(va.x);
Console.WriteLine(va.y);
}
}
In the above listing, the variables x and y are declared outside the Main() method. Hence, they are called as Instance variables. You need to create an object only for accessing an Instance variable. As soon as you create a variable, .NET allocates memory and it is immediately destroyed after the execution of the program with the help of the built-in garbage collector.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |