A class is a data structure that allows you to store data and execute code.
C# provides class
as a construct that allows us create our own custom types.
A class contains data members and function members.
A single class can have any number of data and function members.
However, it's important to contain only related data and function members in a class to provide better organization.
In C# we create classes using the class
construct.
We then group together variables, methods and events.
So a class acts like a blueprint.
The data and function members define the data and behaviour a given type.
A class can be declared as static or not.
With static classes we have only a single copy in memory. The calling code can access it only through the class itself.
Non-static classes are also called instance classes. With these, calling code can use the class by instantiating(creating instances/objects) the classes.
With the non-static classes, the variable will then remain in memory untill all references go out of scope.
Then the CLR(Common Language Runtime) will indicate the it needs to be garbage collected.
Classes support inheritance, unlike structs which are also used to create types.
Data Members | description |
---|---|
Fields | Object attributes which may contain data. |
Constants | A value that cannot be altered by the program during normal execution. |
No. | Function Members | Description |
---|---|---|
1. | Methods | A procedure that is defined as part of a class and included in any object of that class. |
2. | Constructors | A special method of a class or structure that initializes an object of that type. |
3. | Destructors | Special Method automatically invoked during the destruction of an object. |
4. | Constructors | |
5. | Operators | A symbol that represents an action. |
6. | Indexers | A class member used to provide array-like indexing capabilities for easy object property access. |
7. | Events | An action that occurs as a result of the user or another source, such as a mouse being clicked, or a key being pressed. |
Classes normally encapsulate logically related data and functions. They generally represent a objects in the real or conceptual world.
Classes are declared using the class
keyword.
public class Spacecraft
{
//Fields, properties, methods and events go here...
}
A class declaration defines the characteristics of the class, and does not create the class instance.
The class declaration provides us with these:
Spacecraft
Take note that the class
keyword is preceded by the access level.
In this case its public
hence anyone(other classes) can create objects.
Then the after that we have the class name/identifier.
Then the class body wrapped in curly braces({}).
namespace What_is_Class
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello World");
System.Console.ReadLine();
}
}
}