Vous êtes sur la page 1sur 12

A Basic Introduction of Class for Beginners.

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 its 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.
Hide Copy Code

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.
Hide Copy Code

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, thats why the allocation of class doesnt 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 cant 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 weve 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

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:
Hide Copy Code

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:
Hide Copy Code

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
Hide Copy Code

// 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 variables type.
Instantiation: new is a operator that creates the new object (allocates space for it)
Initialization: Program() is a call to Programs constructor, which initializes the object.

here, Declaration doesnt create a new object of class,


Program obj doesnt 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

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
Hide Copy Code

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.
Hide Copy Code

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 dont 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 cant create an instance of abstract class by using new keyword. if you will try,it will give compile
time error.

Some Point
Why we cant 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
Hide Copy Code

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
Hide Copy Code

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.
Hide Copy Code

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
Hide Copy Code

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# doesnt support Multiple Inheritance. You can use Interface to support Multiple Inheritance in your
Program.
Why doesnt C# support multiple inheritance?

Defining a subclass
A subclass is defined as follows
Hide Copy Code

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 subclassname. while implemented the subclass will contain its own members as well those of the baseclass.
Hide Copy Code

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
Hide Copy Code

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 cant 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 understood:

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

Vous aimerez peut-être aussi