Click here to Skip to main content
Click here to Skip to main content

Tagged as

A Basic Introduction of Class for Beginners.

, 27 Feb 2012
Rate this:
Please Sign up or sign in to vote.
A blog enable you to understand about concept of classes.

Introduction

As we know C# is a true object-oriented language, therefore everything must be placed inside a class. Basically a class is a user defined data type with a template that serves to define its properties. In short class is nothing it’s just a kind of template for object (as what an object look like and how it behaves) which we create in program, a kind of specification or blue print which must be followed by object created for correspondence class.

class classname
{
//here define member of class
[variable declaration;]
[methods declarations;]
}

While creating class the first step is used which is declaring class keyword and then name of class or identifier. After declaring class name the next step is declaring body of class which will start with opening curly braces { and also end with closing curly braces }.

We need to declare body inside opening and closing curly braces.

class program { }

Here class is a keyword and program is valid C# identifier. Class and structs are very similar but class is a reference type. Also classes include more features compared to structs. Have a look at some categories of class member.

Fig: Class Members

Note:C# classes are reference types, that’s why the allocation of class doesn’t exist in Stack class are always allocated on the Managed Heap. The Managed Heap is an area of memory that is managed by the CLR( Common Language Runtime), which has the ability to free unused memory blocks (objects) in a process known as Garbage Collecti

The Class Name

The class keyword is followed by the name of the class keyword. in the given code Program is the class. While creating class we must consider naming convention and rule.

Class Naming Conventions

Class names should follow certain naming conventions or guidelines.

A class name :

  • Should be meaningful(strongly recommended)
  • Should ideally be a noun.
  • Can use either the Pascal case or Camel Case.

Rules for Naming classes in C# Name of Classes :

  • Must begin with a letter. This letter may be followed by a sequence of letters, digits (0-9) or “-”.
  • The first character in a class name cannot be a digit.
  • Must not contain any embedded space or symbol like ?-+!@$%^&*(){}[],;”‘/ and \ however an underscore (‘_’) can be used wherever a space is required.
  • Must not use a keyword for a class name. For example you can’t declare a class called public.

For more reference, Have a read
MSDN-[ Names of Classes ]
MSDN-[ Naming Guidelines ]
Naming Conventions for C#

A example of class structure in Program

Fig: Example of Class Structure

The Using Keyword

First statement in a typical C# program is using System; the using keyword is used to include the namespace in the program. Keywords are reserved words that have a special meaning, The statement using system, declares that you can refer to the class defined in the namespace without using the fully qualified name. A program can include multiple using statements.

For more reference. have a read
MSDN-[ using (C# Reference) ]
The “using” Keyword in C#

The Namespace Keyword

The namespace keyword is used to declare a namespace in a program. Generally namespace is a collection of class. A program can contain multiple namespace.

For more reference, have a read
MSDN-[ Namespace ]

The class Keyword

The class Keyword is used to declare a class.

For more reference, Have a look at
MSDN-[ class (C# Reference) ]

The Comment Entry

Comment are a part of the program and are used to explain code. Compilers ignore comment entries.

for more reference, have a read
MSDN-[ Adding Comments in C# Code ]

Member Variables

Variables are used to store data. Variables are also called the data members of a class.

for more reference, have a read
MSDN-[ Variables ]

Member Functions

A function is a set of statement that perform a specific task in response to a message. The function of a class is called member function in C#.

for more reference, have a read
MSDN-[ Methods (C# Programming Guide) ]

Constructor:

A constructor is a special type of method which call itself when you create a new instance of a class. The name of a constructor is the same as the name of the class that contain it.
MSDN-[Constructors (C# Programming Guide)]
Constructor in OOPL

Class and Objects

Classes are like the heart of an OOPL(object Oriented Programming Language). we need to use it even we write simplest of program where objects of class provides the benefit of modularity and information hiding where as class provides the benefit of reusuability. we programmer used the same class same code and over again to create many objects.
The class is declared with the Main() Method and it got initiated in same class. The First line of code that a C# compiler looks in the source file compiled is the Main() function. To use a class the members of a class, you need to create an object of the class. Objects interact with each other by passing messages and by responding to the received messages. Objects use methods to pass messages. In C# the task of passing messages can be accomplished by using member functions. All the object of a class share the same copy of the member function but they maintain a separate copy of the number variables in memory. The sharing of member function and non sharing of member variables of classes and object in shown in the following figure :

Fig: Objects of Class

What is Object

A object is refer as an instance of an executable copy of class or an object is a software bundle of variables and related methods where object maintain its state in variable and implement its behavior with methods.

How to create Object

Let take a look at below animated image where a class is laptop would declare the instance variable to contain the details of webcam, the screen size, Brand,Color, Ram and corresponding processor. The class also can contain some appropriate methods.

After we’ve created the Laptop class, we can create any number of Laptop objects from the class. When we create an instance of a class, the system allocates enough memory for the object and all its instance variables. Each instance gets its own copy of all the instance variables defined in the class.
In addition to instance variables, classes can define class variables. A class variable contains information that is shared by all instances of the class.
Take a look at below image, Where I tried to clear concept by using two object objcet1 and object2 where each containing its own details like object1 has Intel I3 Processor whereas object2 has AMD processor

classobject.gif

Animated Image - Example of class

Illustration with Codes

Creating Object of Class

While we create a class, we used to create a data type which is just a declaration. We can create object of this data type. Creating object is a two-step process, which is given below:

  • First declare a variable of type class. When we do so we are actually creating a reference that will refer to an object. In the corresponding slide this is done in Main( ) through the following statement:
    Program obj;
    
  • In Second step, allocate memory for an object and assign it to the reference. Allocating memory for an object is done using the new operator. new dynamically allocates memory for an object and returns its reference. So, every object is referred to by a reference only. In the corresponding slide we have created an object of the Program class through the statement:
     obj = new Program( ) ;
    

When the above statement is executed, an object gets created in memory, as you can see in the figure, which is referred to by obj.

Using obj we have called the setdata( ) and showdata( ) member functions of the Program class. In the setdata( ) function we have stored some values in the data members name and age. In the showdata( ) function we have displayed the values.

Hence, we can say that

// Creating Instance of Class
Program obj = new Program();
  • Declaration: Program obj is a variable declaration that declares to the compiler that the name obj will be used to refer to a Program object. Notice that a class name is used as the variable’s type.
  • Instantiation: new is a operator that creates the new object (allocates space for it)
  • Initialization: Program() is a call to Program’s constructor, which initializes the object.

here, Declaration doesn’t create a new object of class,
Program obj doesn’t create new object of Program class. Just a variable name obj to holds a Program object.

Note: To create class object or any other object, we need to use the new operator The member function of the class are accessed through an object of the class by using the “.” Operator. As shown below

Multiple Object of Class

Multiclassobject.gif

Animated Image - Multiple Object of Class

In the above figure we can see that Program have two objects of the class Program, which are referred by obj1 and obj2 . We have followed the same way to create these objects as previous program. i.e first declaring the references and then assigning to them the address of objects created using new.
Both the objects have their own copies of data members.

Constructor

A constructor is a special member function of a class, which gets called automatically when an object is created. Hence, a constructor is used to set up values into an object. A constructor has the same name as the class.
It would become tedious to call a separate function every time to assign initial values to the objects. What if we would be able to initialize the objects when they are created? This can be done using constructors

class Program
    {
        string name;
        int age;
        Program(string n,int a)
        {
            name = n;  // assigning value to name
            age = a;  // assigning value to age
        }
        public void showdata()
        {
            Console.WriteLine(name+" "+age);
        }
}

Here, as soon as the statement, new Program( ), gets executed the constructor of Program class gets called. In the constructor we have assigned values to the data members. The values are displayed using the showdata( ) function. The only problem is that all the objects of the Program class would get initialised with the same values We would not be able to assign different values to the objects.
To overcome this problem we would need a constructor to which we can pass values as we did in the setdata( ) function.

static void Main(String[] args)
       {
           Program obj = new Program("Ram", 20);
           obj.showdata();
        }

have a look at given image to know how value pass between Member variables using Constructor.

Class and its Accessibility

while defining class, each class need to specify its level of visibility. class visibility is used to decide which parts of the system can create class objects.
A class can have one of the two visibility modifiers : public or internal.

Note: if we don’t explicitly mention visibility modifier of a class, its implicitly set to ‘internal’. 1.e by default all classes are internal.

Fig: Accessibility of class members

abstract: An abstract class is same as others classes but its marks with abstract keyword. abstract class can have normal properties, constructor and other methods. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. abstract class is the way to make sure that its closed subclass must override abstract method. In sense, if you want our subclass have which method to overridden, we have to make that methods and the superclass to be abstract.

Note: we can’t create an instance of abstract class by using new keyword. if you will try,it will give compile time error.

Some Point

Why we can’t I create an abstract constructor on an abstract C# class. check answer because abstract means you must override it in any non-abstract child class and you cannot override a constructor.

for more reference, have a look at
MSDN-[ abstract class ]
Abstract Class
All about abstract classes.

sealed: A sealed class is is declared with sealed keyword, The sealed modifier can be applied to class, instances methods and properties. A sealed class cannot be used as a base class or sub classed. it means a sealed class cannot be inherited by anyway. Sealed classes are primarily used to prevent derivation

 sealed class A
   {
        // member function
   }
  class B : A //Error : Class B can't derive from sealed type class A
   {
   }

here Child class can be sealed but when child class B try to act as parent class it will give same error. as

 sealed class A
   {        // member function
   }
  class B : A
   {  }
 class C:B //Error
  { }

Question in Mind: Do sealed classes really offer performance Benefits? [Click link to get answer ]

for more reference, must see
MSDN-[ sealed (C# Reference) ]

singleton class : singleton class is used to ensure that only one instance of a class is can be created

for more reference, Implementing Singleton in C#
explain singleton pattern
Exploring the Singleton Design Pattern

Generic class : Generic classes is generally used to encapsulate operations that are not specific to a particular data type. The most common use of generics is to create collection classes.

for more reference, Generic Classes

Interface

An Interface is a logical group of related methods with empty bodies. it can contain one or more methods,properties, indexers and events but none of them are implemented in the interface in it self. Its the responsibility of class that implement the interface to define the code for implementation of these members.

interface InterfaceName
{
// Member declaration
//Properties Indexer and events declarations
}

here, Interface is the keyword and InterfaceName is the valid identifier (same as Class Name ) where member declaration contain only a list of members without any implementation of codes.

example

interface Iface
{
void setdata(); // Note semicolon here
}

Fore more reference, have a read
MSDN-[Interfaces]
Abstract Class versus Interface

Inheritance

Inheritance represents a kind of relationship between two classes. The mechanism of designing or constructing one class from another is called inheritance.
Related to Inheritance is an equally feature known as polymorphism. this feature permists the same method name to be used for different operations in different derived classes.
There are some various kind of Inheritance. they include

  • Single Inheritance (only one base class ).
  • Hierarchical Inheritance ( one base class, Many subclasses ).
  • Multilevel Inheritance (derive from a derived class ).

Note: C# doesn’t support Multiple Inheritance. You can use Interface to support Multiple Inheritance in your Program.

Why doesn’t C# support multiple inheritance?

Defining a subclass

A subclass is defined as follows

class subclass-name : baseclass-name
{
variables declaration;
methods declaration;
}

Here, you can see that the desecration is very similar to a normal class definition except for the use of colon : and baseclass-name. the colon signifies that the properties of the baseclass are extended to the subclass-name. while implemented the subclass will contain its own members as well those of the baseclass.

class Animal{
void Disp_animal(){
Console.WriteLine("Hello I am Animal Class");
}
}
class Lion:Amimal
{
void Disp_lion(){
Console.WriteLine("Hello I am derived lion class"");
}
}

while excessive each function of corresponding class

Lion obj = new Lion();
obj.Disp_animal();// object of child class accessing parent class function.
obj.Disp_lion();

Some features of inheritance :

  • constructor and destructors are not inherited.
  • A derived class extends its direct base class. it can’t change or remove the definitions of an inherited member.
  • An instance of a class contain a copy of all instance fields declared in the class and its base classes.
  • A derived class can hide an inherited member.
  • A derived class can override an inherited member.

For more reference, have a read What is Inheritance?

What you Got

You should have a general understanding or a feeling for the following:

  • What is class
  • How to create an object from a class
  • What constructors are
  • What the code for a class looks like
  • What member variables are
  • How to initialize objects
  • basic Idea of Inheritance

History

  • 24 Feb 2012 - Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

RaviRanjankr
Software Developer
India India
Microsoft Student Partner | CS Student | MCTS | CP MVP | Crazy Learner | Dreamer
 
An Indian, who loves his country, believes in freedom, He is an enthusiast Techie and crazy learner. He is passionate about Technologies and social media. He holds bachelor degree of CS in Information Technology and now pursuing Master degree in Computer Application.
 
He always excited and keen Interested in learning and sharing knowledge. He loves to write blog, learn new things, listen music, taking arts and Playing Games..
 
He keep himself on the desk of his imagination, hanging around with some inceptions.
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberSZenah6-May-12 8:50 
GeneralRe: My vote of 5 PinmvpRaviRanjankr21-Oct-12 20:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140902.1 | Last Updated 27 Feb 2012
Article Copyright 2012 by RaviRanjankr
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid