Classes in C#

Introduction to Classes in C#

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.

  1. Data Members - Store data associated with the class of an instance of the class. They represent teh real world properties of the object.
  2. Function Members - These are deal with code execution. They represent the actions of the objects.

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.

Possible Contents of a Class

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.

Clas Declaration

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:

  1. Class name e.g Spacecraft
  2. Member and Characteristics of the class.

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({}).

Example

namespace What_is_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello World");
            System.Console.ReadLine();
        }
    }
}

Data Members

Types can be divided generally into two:

  1. Simple Types - Can store only a single data item.
  2. Non-Single Types - Can store multiple items.

The multiple elements that can be stored by non-single types are called members.

Types of Members

The members can be divided into two:

  1. Data Members - These store data relevant to the object of the class or the class as whole.
  2. Function Members - These members define the behavior of a type.

Declaration and Instantiation

Support for classes and objects(created from those classes) is the core construct of any C# program.

And indeed is what makes C# an object-oriented programming language.

Classes are templates for Object creation.
Classes allow us create larger more organized programs that are easier to maintain.

In that 1970s and 1980s, transition from sturctured, control-flow based programs to object-oriented programs revolutionized programming since it provided an extra-level of orgnanization.

Proframs were simplified and it was easier than ever to create large programs due to this better organization.

Classes are the most fundamental construct in Object-Oriented programs. It is the clases that form the abstraction or template of a real-world concept.

Declaring Classes

To declare a class is to define a class.

We use the the class keyword for this.

Here's how you define a class:

class Spaceship
{

}
  1. First you specify the class keyword.
  2. You follow it with the identifier or name of the class. e.g Spacecraft.
  3. Then curly braces to signify the class body. This is where the code that belongs to the class will be written.

Most of the time people prefer to place each class in its own file. I's not a requirement, however it's normally recommended unless the class you create is super simple.

If you place a class inside it's own file then the convention is to always name the class as you named the file.

Having defined a class, you can:

  1. declare a variable of that type.
  2. define a method that takes as a parameter or returns that type.
 class Program
    {
        static Spaceship GetLocation(Spaceship spaceship)
        {
            return spaceship;
        }
        static void Main(string[] args)
        {
            Spaceship casini, kepler;
        }
    }

Instantiating classes

So far we've created a class. However classes are just templates for creation of objects.

C# is an object-oriented programming language, and it is the objects that do stuff.

An object is basically an instance of the class. Classes mold what objects do.

The process of creating an object from a class is what is called insantiation.

To create or instantiate a class to produce an object, we use the new keyword in C#.

using System;

namespace MrClass
{
    class Spaceship
    {

    }
    class Program
    {
        static Spaceship GetSpaceship(Spaceship spaceship)
        {
            return spaceship;
        }
        static void Main()
        {
            Spaceship casini = new Spaceship();
            Spaceship kepler;
            kepler = new Spaceship();
            Console.WriteLine(GetSpaceship(casini).GetType());
            Console.ReadLine();
        }
    }
}

Result

MrClass.Spaceship
  1. The assignment can occur in the same statement or in a separate statement.
  2. The new keyword tells the runtime to allocate memory for a Spaceship object, instantiate the object and return a reference to the instance.
  3. Memory gets allocated by the runtime when we explicitly use the new keyword to create an object, however deallocation is handled automatically be the runtime without us doing anything. This, the runtime does after an object is marked inaccessible.
    This deallocation is handle by the garbage collector. It checks which objects are no longer referenced by other active objects and then deallocates the memory of those objects.

Object Initializer

Normally you use a constructor allows you to specify startup values when creating an object.

On the other hand properties allow you to set or get the underlying data of an object in a safe manner.

However, it's not easy to create a single constructor that sets the underlying state data of an object. Even if it could be easy it doesn't look tidy doing it that way.

C# provides us a cleaner syntax that streamlines this process of getting our object up and running. This syntax is the Object Initializer Syntax.

With this it's possible to create an object and set a slew of properties to the object to it.

How does Object Initializer look like?

An object initializer comprises a comma-delimmited list of values enclosed by double curly braces({}) tokens.

Every member in the initialization syntax will map to the name of a public field or public property of the given object.

Advantages of Object Initializer

No. Advantage
1. It's much tidy and cleaner.
2. It's much more concise and allows us write less lines of code.

Examples

Say I want to create a Windows Forms with a slew of propeties:

Form myForm = new Form()
{
   Text = "Object Initializer Example",
   ClientSize = new Size(560, 430),
};

In the above we have set the Text and ClientSize public properties via the Object initializer syntax.

Or a combobox with properties in one line :

comboBox = new ComboBox { Location = new Point(164, 176) ,DropDownStyle = ComboBoxStyle.DropDownList};

In this one we have set the Location and DropDownStyle public properties of our ComboBox via the Object initializer syntax.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *