The document discusses key concepts of classes and objects in C# including defining classes, adding variables and methods, member access modifiers, creating objects, constructors, static members, private constructors, and indexers. It defines classes as user defined data types that can encapsulate data as fields and functions as methods. Objects are instances of classes that allow data and methods to be accessed. Constructors initialize objects, while static members are associated with the class rather than individual objects.
Overview of C# programming focusing on classes and objects; C# is object-oriented, using classes to encapsulate data (fields) and operations (methods).
Core principles of OOP: Encapsulation (data hiding), Inheritance (creating new classes), Polymorphism (objects taking multiple forms).
How to define a class in C#, including template structure; data encapsulation via instance variables without allocated storage initially.
Importance of methods within classes to enable interaction; methods defined within classes operate on data and must be accessible.
Access modifiers (public, private, protected) control visibility of class members to enforce encapsulation.
Instantiation of objects using the 'new' operator; accessing methods and variables of class objects.
Practical applications showcasing the use of classes and objects in C# programming.
Constructors initialize object state; constructors share names with their class and can be overloaded to handle different initialization scenarios.
Static members share a single class-wide storage; they behave differently compared to instance members and methods.
Static constructors initialize class-level static members before instance creation; lack parameters and access modifiers.
Copy constructors facilitate object duplication; private constructors limit instantiation, typically for utility classes.
Example of a class with a private constructor demonstrating controlled instantiation; allows only specific methods to create objects.
Introduction to destructors for memory management, noting C#’s garbage collector.
Explains 'this' reference in instances; indexers allow objects to be indexed like arrays with defined accessors.
Dr. Neeraj KumarPandey
https://www.slideshare.net/nkpandey
Classes & Objects in C#
2.
INDEX
• Introduction.
• BasicPrinciple of OOP.
• Defining a Class.
• Adding variables and methods.
• Member access modifier.
• Creating objects and accessing class members.
• Constructors.
• Static Members.
3.
Introduction
C# isa true object oriented language.
C# program must be encapsulated in a class that defines the state and behaviour of
the basic program components known as objects.
Classes creates objects and objects use methods to communicate between them.
Classes provide a convenient approach for packing together a group of logically
related data items and functions that work on them.
In C# data items are called fields and the functions are called methods.
4.
Basic Principles ofOOP
All object-oriented languages employ three core principles
Encapsulation: Provides the ability to hide the internal details of an object
from its user. The outside user may not be able to change the state of an object
directly. Encapsulation is implemented using the access modifier keywords public,
private and protected. The concept of encapsulation is also known as data hiding
or information hiding.
Inheritance: It is the concept we use to build new classes using the existing
class definitions. Through inheritance we can modify a class the way we want to
create new objects. The original class is known as base or parent class and the
modified one is known as derived class or subclass or child class.
Polymorphism: it is the third concept of OOP. It is the ability to take more
than one form.
5.
Defining a class
-Class is user defined data type with a template that serves to define its
properties.
- One the class type has been defined we can create ‘variables’ of that
type using declaration that are similar to the basic type declaration.
- In C# these variables are termed as instances of classes, which are the
actual objects.
class classname
{ [variables declaration;]
[methods declaration;
}
class is a keyword and classname is any valid c# identifier. Everything inside
the square brackets is optional
class Empty
{
} is also a valid class definition
6.
Adding Variables
• Datais encapsulated in a
class by placing data fields
inside the body of the
class definition .
Class reactangle
{ int length; //instance variable
int width; //instance variable
}
These instance variable is also
known as member variable and
no storage space has been
created.
7.
Adding Methods
• Aclass with only data fields and without methods that operates on
that data has no life.
• The objects created by such class can not respond to any
messages.
• Methods are declared inside the body of the class , usually after
the declaration of instance variables.
type methodname (parameter-list)
{
method-body;
}
Example:
class rectangle
{ int length;
int width;
public void GetData(int x, int y)
{ length=x; width=y;
}
Public int RectArea()
{ int area= length*width;
return(area)
} }
8.
Adding Methods (contd..)
Instance variables and methods in classes are accessible by all the
methods in the class, but a method can not access the variables
declared in other methods.
9.
Member Access modifiers
-A class may be designed to hide its members from outside
accessibility .
- C# provides a set of access modifiers that can be used with the
members of a class to control their visibility to outside users.
- In C# all members have private access by default.
10.
Creating Objects
Creatingan objects is also referred to as instantiating an
object.
object in C# created using the new operator.
The new operator creates an object of the specified class
and returns a reference to that object.
Ex. Rectangle rect1; //declare
react1=new Rectangle( );
OR
Rectangle R1=new Reactangle( );
Rectangle R2=R1;
Constructors
• Initialization ofall objects can be done by two
approaches.
• First Approach uses the dot operator to access
the instance variables and then assigns value to
them individually.
• Second approach takes the help of a function
like GetData to initialize each object.
• Both the approaches are tedious to initialize
objects.
14.
Constructors (contd..)
• C#supports a special type of method, called constructor. That enables an object to initialize
itself when it is created.
• Constructor have same name as the class itself.
• They do not specify a return type, not even void.
• By default constructors are public but they can also be declared as private or protected.in such
cases , the objects of that class can not be created and also the class can not be used as a base
class for inheritance.
class Rectangle
{ public int length; public int width;
public Rectangle(int x, int y)
{
length=x; width=y;
}
public int RectArea( )
{
return(length*width);
}
}
15.
Overloaded Constructors
• InC# , it is possible to create methods that have the same name, but different parameter lists and different
definitions. (Method overloading).
• Method overloading can be used when objects are required to perform similar tasks but using different
parameters.
• Similarly we can create overloaded constructor method by providing several different constructor definitions
with different parameter lists.
class Rectangle
{ public int length; public int width;
public Rectangle(int x, int y)
{
length=x; width=y;
}
public Rectangle(int x)
{
length=width=x;
}
public int RectArea( )
{
return(length*width);
}
}
16.
Static Members
• Classcontains two sections. one declares variables (instance
variables)and other declares methods(instance methods).
• Every time the class is instantiated , a new copy of each is
created and accessed using dot operator.
• static members and static methods are declared by using a
keyword static.
• static variable are associated with the class itself rather than
with individual objects.
• static variables and static methods are referred as class
variables and class methods.
• static variables are used when we want to have a variable
common to all instances of a class.
• static method can be called without using the objects.
• They are also for use by other classes.
17.
Static Members (contd..)
usingsystem;
class XYZ
{
public static int mul(int x,int y)
{ return (x*y); }
public static float div(float x,float y)
{ return (x/y); }
}
class Calculation
{
public void static Main()
{ int a=XYZ.mul(4,5);
float b = XYZ.div(3.4F,1.7F);
Console.WriteLine(“a={0} and b={1}”,a,b);
}
Note: Static methods are called using class names.
static methods have following restrictions
1. They can only call other static methods.
2. they can only access static data.
3. they can not refer to this or base in any ways.
18.
Static constructors
staticconstructor is called before any object of the class is created.
static constructor is declared by prefixing a static keyword to the constructor definition.
it can not have any parameters.
Example:
class abc
{
static abc( ) //no parameters
{
………… //set value for static members
…………
}
}
• A static constructor does not take
access modifiers or have
parameters.
• A static constructor is called
automatically to initialize
the class before the first instance is
created or any static members are
referenced.
• A static constructor cannot be
called directly.
• The user has no control on when
the static constructor is executed in
the program.
• A typical use of static constructors
is when the class is using a log file
and the constructor is used to write
entries to this file.
19.
Copy Constructor
Acopy constructor creates an object by copying variables from another object
C# does not provide a copy constructor .
if we wish to add this feature to the class . A copy constructor is defined as follows
public Item (Item item)
{
code =item.code;
price =item.price;
}
copy constructor is invoked by instantiating an object of type Item and passing it the
object to be copied.
Item item2=new Item (item1);
now item1 is copy to item2.
Destructor: As C# manages the memory dynamically and
uses a garbage collector, running on a separate thread to
execute all destructor on exit.
20.
Private Constructor
C#does not have global variables or constants.
All declarations must be contained in a class.
In many situations we define some utility classes that contains only
static members.
object of a class having private constructor cannot be instantiated from
outside of the class. However, we can create object of the class inside
class methods itself.
Private constructor is constructor that is preceded by private access
specifier.
21.
Private Constructorusing System;
namespaceXYZ
{
class User
{
// private Constructor
private User()
{
Console.WriteLine("Private Constructor");
}
public static string name, location;
// Default Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}
class Program
{
static void Main(string[] args)
{
// The following comment line will throw an error
// because constructor is inaccessible
//User user = new User();
// Only Default constructor with parameters will invoke
User user1 = new User(“JITIN KUMAR", “NEW DELHI");
Console.WriteLine(User.name + ", " + User.location);
Console.WriteLine("nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
Indexers
• Indexer Conceptis object act as an array.
• Indexer an object to be indexed in the same way as an array.
• Indexer modifier can be private, public, protected or internal.
• The return type can be any valid C# types.
• Indexers in C# must have at least one parameter. Else the compiler will generate a
compilation error.
this [Parameter]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}