SlideShare a Scribd company logo
Dr. Neeraj Kumar Pandey
https://www.slideshare.net/nkpandey
Classes & Objects in C#
INDEX
• Introduction.
• Basic Principle of OOP.
• Defining a Class.
• Adding variables and methods.
• Member access modifier.
• Creating objects and accessing class members.
• Constructors.
• Static Members.
Introduction
 C# is a 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.
Basic Principles of OOP
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.
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
Adding Variables
• Data is 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.
Adding Methods
• A class 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)
} }
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.
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.
Creating Objects
 Creating an 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;
Accessing Class Members
objectname.variable_name;
objectname.methodname(parameter-list);
example.
Rectangle rect1=new Rectangle( );
Rectangle rect2= new Rectangle();
rect1.length = 15; rect2.length =20
rect1.width = 10; rect2.width = 12
Application of Classes and Objects
Constructors
• Initialization of all 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.
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);
}
}
Overloaded Constructors
• In C# , 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);
}
}
Static Members
• Class contains 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.
Static Members (contd..)
using system;
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.
Static constructors
 static constructor 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.
Copy Constructor
 A copy 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.
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.
Private Constructorusing System;
namespace XYZ
{
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();
}
}
}
Destructors
The This Reference
Indexers
• Indexer Concept is 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
}
}
C#  classes objects

More Related Content

What's hot (20)

PPTX
Java abstract class & abstract methods
Shubham Dwivedi
 
PPTX
Operator overloading
Ramish Suleman
 
PPT
Java interfaces
Raja Sekhar
 
PPT
Introduction To C#
SAMIR BHOGAYTA
 
PPTX
This keyword in java
Hitesh Kumar
 
PPTX
Java - Generic programming
Riccardo Cardin
 
PPTX
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
PPTX
Interfaces in java
Abishek Purushothaman
 
PDF
Generics
Ravi_Kant_Sahu
 
PPTX
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
PPTX
Java constructors
QUONTRASOLUTIONS
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPTX
Interface in java
PhD Research Scholar
 
PDF
Arrays in Java
Naz Abdalla
 
PPTX
Strings in c#
Dr.Neeraj Kumar Pandey
 
PPT
Abstract class
Tony Nguyen
 
PPTX
Asp.NET Validation controls
Guddu gupta
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPTX
Inheritance in java
Tech_MX
 
Java abstract class & abstract methods
Shubham Dwivedi
 
Operator overloading
Ramish Suleman
 
Java interfaces
Raja Sekhar
 
Introduction To C#
SAMIR BHOGAYTA
 
This keyword in java
Hitesh Kumar
 
Java - Generic programming
Riccardo Cardin
 
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
Interfaces in java
Abishek Purushothaman
 
Generics
Ravi_Kant_Sahu
 
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Java constructors
QUONTRASOLUTIONS
 
Classes, objects in JAVA
Abhilash Nair
 
JDBC – Java Database Connectivity
Information Technology
 
Interface in java
PhD Research Scholar
 
Arrays in Java
Naz Abdalla
 
Strings in c#
Dr.Neeraj Kumar Pandey
 
Abstract class
Tony Nguyen
 
Asp.NET Validation controls
Guddu gupta
 
9. Input Output in java
Nilesh Dalvi
 
Inheritance in java
Tech_MX
 

Similar to C# classes objects (20)

PPT
C++ classes tutorials
akreyi
 
PPTX
Quick Interview Preparation for C# All Concepts
Karmanjay Verma
 
PPTX
OOP in C# Classes and Objects.
Abid Kohistani
 
PDF
Object Oriented Programming with C#
SyedUmairAli9
 
PPTX
Better Understanding OOP using C#
Chandan Gupta Bhagat
 
PDF
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
PPT
Constructor
abhay singh
 
PPTX
CSharp presentation and software developement
frwebhelp
 
PPTX
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
PPT
CSharp_03_ClassesStructs_and_introduction
Ranjithsingh20
 
PDF
C# Summer course - Lecture 3
mohamedsamyali
 
PPTX
Object-oriented programming 3.pptx
Adikhan27
 
PPTX
Oops
Gayathri Ganesh
 
PPTX
Notes(1).pptx
InfinityWorld3
 
PPT
Object Oriented Programming In .Net
Greg Sohl
 
PPTX
Object-Oriented Programming with C#
Svetlin Nakov
 
PPTX
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
PPTX
C# - Igor Ralić
Software StartUp Academy Osijek
 
PDF
Learn C# Programming - Classes & Inheritance
Eng Teong Cheah
 
PPTX
Objects and Types C#
Raghuveer Guthikonda
 
C++ classes tutorials
akreyi
 
Quick Interview Preparation for C# All Concepts
Karmanjay Verma
 
OOP in C# Classes and Objects.
Abid Kohistani
 
Object Oriented Programming with C#
SyedUmairAli9
 
Better Understanding OOP using C#
Chandan Gupta Bhagat
 
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
Constructor
abhay singh
 
CSharp presentation and software developement
frwebhelp
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
CSharp_03_ClassesStructs_and_introduction
Ranjithsingh20
 
C# Summer course - Lecture 3
mohamedsamyali
 
Object-oriented programming 3.pptx
Adikhan27
 
Notes(1).pptx
InfinityWorld3
 
Object Oriented Programming In .Net
Greg Sohl
 
Object-Oriented Programming with C#
Svetlin Nakov
 
03 classes interfaces_principlesofoop
Vladislav Hadzhiyski
 
Learn C# Programming - Classes & Inheritance
Eng Teong Cheah
 
Objects and Types C#
Raghuveer Guthikonda
 
Ad

More from Dr.Neeraj Kumar Pandey (18)

PPTX
Structure in c#
Dr.Neeraj Kumar Pandey
 
PPTX
Program control statements in c#
Dr.Neeraj Kumar Pandey
 
PPTX
Operators and expression in c#
Dr.Neeraj Kumar Pandey
 
PPTX
Method parameters in c#
Dr.Neeraj Kumar Pandey
 
PPTX
Enumeration in c#
Dr.Neeraj Kumar Pandey
 
PPTX
Dot net assembly
Dr.Neeraj Kumar Pandey
 
PPT
Cloud introduction
Dr.Neeraj Kumar Pandey
 
PPTX
Role of cloud computing in scm
Dr.Neeraj Kumar Pandey
 
PPTX
Public cloud
Dr.Neeraj Kumar Pandey
 
PPTX
cloud computing Multi cloud
Dr.Neeraj Kumar Pandey
 
PPTX
Ibm bluemix case study
Dr.Neeraj Kumar Pandey
 
PPTX
Business cases for the need of cloud computing
Dr.Neeraj Kumar Pandey
 
PPT
cloud computing:Types of virtualization
Dr.Neeraj Kumar Pandey
 
PPTX
cloud computing: Vm migration
Dr.Neeraj Kumar Pandey
 
PPTX
Cloud Computing: Virtualization
Dr.Neeraj Kumar Pandey
 
PPT
Dot net introduction
Dr.Neeraj Kumar Pandey
 
PPTX
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
PPTX
C# lecture 1: Introduction to Dot Net Framework
Dr.Neeraj Kumar Pandey
 
Structure in c#
Dr.Neeraj Kumar Pandey
 
Program control statements in c#
Dr.Neeraj Kumar Pandey
 
Operators and expression in c#
Dr.Neeraj Kumar Pandey
 
Method parameters in c#
Dr.Neeraj Kumar Pandey
 
Enumeration in c#
Dr.Neeraj Kumar Pandey
 
Dot net assembly
Dr.Neeraj Kumar Pandey
 
Cloud introduction
Dr.Neeraj Kumar Pandey
 
Role of cloud computing in scm
Dr.Neeraj Kumar Pandey
 
cloud computing Multi cloud
Dr.Neeraj Kumar Pandey
 
Ibm bluemix case study
Dr.Neeraj Kumar Pandey
 
Business cases for the need of cloud computing
Dr.Neeraj Kumar Pandey
 
cloud computing:Types of virtualization
Dr.Neeraj Kumar Pandey
 
cloud computing: Vm migration
Dr.Neeraj Kumar Pandey
 
Cloud Computing: Virtualization
Dr.Neeraj Kumar Pandey
 
Dot net introduction
Dr.Neeraj Kumar Pandey
 
C# lecture 2: Literals , Variables and Data Types in C#
Dr.Neeraj Kumar Pandey
 
C# lecture 1: Introduction to Dot Net Framework
Dr.Neeraj Kumar Pandey
 
Ad

Recently uploaded (20)

PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 

C# classes objects

  • 1. Dr. Neeraj Kumar Pandey https://www.slideshare.net/nkpandey Classes & Objects in C#
  • 2. INDEX • Introduction. • Basic Principle of OOP. • Defining a Class. • Adding variables and methods. • Member access modifier. • Creating objects and accessing class members. • Constructors. • Static Members.
  • 3. Introduction  C# is a 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 of OOP 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 • Data is 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 • A class 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  Creating an 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;
  • 11. Accessing Class Members objectname.variable_name; objectname.methodname(parameter-list); example. Rectangle rect1=new Rectangle( ); Rectangle rect2= new Rectangle(); rect1.length = 15; rect2.length =20 rect1.width = 10; rect2.width = 12
  • 12. Application of Classes and Objects
  • 13. Constructors • Initialization of all 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 • In C# , 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 • Class contains 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..) using system; 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  static constructor 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  A copy 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; namespace XYZ { 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(); } } }
  • 24. Indexers • Indexer Concept is 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 } }