SlideShare a Scribd company logo
11
Introduction to
Object Oriented Programming in C#
By Anurag Singh
22
Objectives
You will be able to:
1. Write a simple class definition in C#.
2. Control access to the methods and data
in a class.
3. Create instances of a class.
4. Write and use class constructors.
5. Use the static keyword to create class
members that are not associated with a
particular object.
33
What is a class?
Essentially a struct with built-in functions
class Circle
{
double radius = 0.0;
double Area()
{
return 3.141592 * radius * radius;
}
}
44
Encapsulation
By default the class definition encapsulates, or
hides, the data inside it.
Key concept of object oriented programming.
The outside world can see and use the data
only by calling the build-in functions.
 Called “methods”
55
Class Members
Methods and variables declared inside a class are
called members of that class.
 Member variables are called fields.
 Member functions are called methods.
In order to be visible outside the class definition, a
member must be declared public.
As written in the previous example, neither the variable
radius nor the method Area could be seen outside
the class definition.
66
Making a Method Visible
To make the Area() method visible outside we would write it as:
public double Area()
{
return 3.141592 * radius * radius;
}
Unlike C++, we have to designate individual members as public.
Not a block of members.
We will keep the radius field private.
7
A Naming Convention
 By convention, public methods and
fields are named with the first letter
capitalized.
 Also class names.
 Private methods and fields are named
in all lower case.
 This is just a convention.
 It is not required, and it means nothing to the compiler.
88
Interface vs. Implementation
 The public definitions comprise the
interface for the class
 A contract between the creator of the class
and the users of the class.
 Should never change.
 Implementation is private
 Users cannot see.
 Users cannot have dependencies.
 Can be changed without affecting users.
99
Creating Objects
 The class definition does not allocate memory
for its fields.
(Except for static fields, which we will discuss later.)
 To do so, we have to create an instance of
the class.
static void Main(string[ ] args)
{
Circle c;
c = new Circle();
}
1010
Objects
An instance of a class is called an object.
You can create any number of instances of a
given class.
 Each has its own identity and lifetime.
 Each has its own copy of the fields associated with
the class.
When you call a class method, you call it through
a particular object.
The method sees the data associated with that object.
1111
Using Classes and Objects
 Classes and objects are used much
like traditional types and variables:
 Declare variables

Like pointers to structs
 Circle c1;

Can be member variables in other classes
 Assignment
c2 = c1;
 Function arguments
picture1.crop(c1);
1212
Program Circle Demo
 Demonstrate creating Program Circle in
Visual Studio.
 Demonstrate adding a class to a project
 Students: Try this for yourself!
13
Create a New Project
14
Create a New Project
15
Program Template
1616
Adding a Class to a Program
 Each class definition should be a
separate file.
 In Visual Studio.
 Project menu > Add Class
 Use class name as file name.
17
Add a Class to the Project
18
Adding Class Circle
19
Initial Source File
20
Fill in Class Definition
21
Fill in Main()
Call function Area() of Circle object c1
22
Build and Run
23
Program circle_demo in Action
Area of Circle c1
2424
So far we have no way to set or change the
value of radius of a Circle.
We can use a constructor to set an initial value.
A constructor is a method with the same name
as the class. It is invoked when we call new
to create an instance of a class.
In C#, unlike C++, you must call new to create an object.
Just declaring a variable of a class type does not create an
object.
Constructors
2525
A Constructor for Class Circle
We can define a constructor for Circle so that it
sets the value of radius.
class Circle
{
private double radius;
...
public Circle (double r)
{
radius = r;
}
...
}
Note: Constructors have no return type.
26
Using a Constructor
Calls constructor
27
Program Running
Area of Circle c1
2828
Multiple Constructors
A class can have any number of constructors.
All must have different signatures.
(The pattern of types used as arguments.)
This is called overloading a method.
Applies to all methods in C#. Not just constructors.
Different names for arguments don’t matter,
Only the types.
2929
Default Constructor
If you don’t write a constructor for a class, the compiler
creates a default constructor.
The default constructor is public and has no
arguments.
c = new Circle();
The default constructor sets numeric variables to
zero and Boolean fields to false.
In constructors that you write, the same is true for
any variables that you don’t initialize.
3030
Creating multiple objects of the same type
31
Program Running
3232
Good Programming Practice
 All member variables should be private.
 except const variables
 Users of the class can use them and
manipulate them only by invoking the
public methods of the class.
 Only way for users to do anything with
an object.
3333
Class Circle
 Let's extend class Circle by providing
names for circle objects.
 Also provide accessor functions
 Public functions that let the outside world
access attributes of an object.
34
Class Circle
New member
New constructor
Accessor
Methods
3535
Getting User Input
 What if we want the user to specify the
radius of a Circle at run time?
 Could overload the constructor and provide
a version that asks for input.
 Better to provide a separate function
outside the class definition.

Separate User Interface from class logic.
 Let’s write a function that asks the user
for a name and a radius and creates a
Circle of that radius with that name.
3636
Getting User Input
static Circle Create_Circle()
{
String name, temp;
double radius;
Console.Write("Please enter name for new Circle: ");
name = Console.ReadLine();
Console.Write("Please enter radius: ");
temp = Console.ReadLine();
radius = double.Parse(temp);
return new Circle(name, radius);
}
In class Program (along with Main() )
37
Main()
static void Main(string[] args)
{
Circle c1 = Create_Circle();
Console.Write("Circle " + c1.Name());
Console.WriteLine(" created with radius " + c1.Radius());
Console.WriteLine("Its area is " + c1.Area());
Console.ReadLine(); // Keep window open.
}
3838
Running Program Circle
End of Section
3939
Passing Objects to a Function
 Let's extend class Circle with a method
to compare one Circle to another.
 In class Circle ...
public bool Is_Greater_Than(Circle other)
{
if (this.Radius() > other.Radius())
{
return true;
}
else
{
return false;
}
}
Note keyword "this" Call Radius() in Circle object
passed as argument.
4040
Using "Is_Greater_Than" Method
static void Main(string[] args)
{
Circle Circle_A = Create_Circle();
Console.Write ("Circle " + Circle_A.Name() );
Console.WriteLine (" created with radius " + Circle_A.Radius());
Console.WriteLine ("Its area is " + Circle_A.Area());
Circle c2= Create_Circle();
Console.Write ("Circle " + c2.Name() );
Console.WriteLine (" created with radius " + c2.Radius());
Console.WriteLine ("Its area is " + c2.Area());
4141
Using "Is_Greater_Than" Method
if (c1.Is_Greater_Than(c2))
{
Console.Write ("Circle " + c1.Name() + " is greater than ");
Console.WriteLine( "Circle " + c2.Name());
}
else if (c2.Is_Greater_Than(c1))
{
Console.Write ("Circle " + c2.Name() + " is greater than ");
Console.WriteLine( "Circle " + c1.Name());
}
else
{
Console.Write("Circle " + c1.Name() + " and Circle " + c2.Name());
Console.WriteLine (" are the same size.");
}
42
Program Running
End of Section
4343
Static Fields
Sometimes we need a single variable that
is shared by all members of a class.
Declare the field static.
You can also declare a field const in
order to ensure that it cannot be
changed.
Not declared static – but is a static variable

There is only one instance
4444
Static Fields
class Math
{
...
public const double PI = 3.14159265358979;
}
In class Circle --
public double Area()
{
return Math.PI * radius * radius;
}
Class name rather than object name.
4545
Static Methods
 Sometimes you want a method to be
independent of a particular object.
 Consider class Math, which provides
functions such as Sin, Cos, Sqrt, etc.
 These functions don’t need any data from
class Math. They just operate on values
passed as arguments. So there is no reason
to instantiate an object of class Math.
4646
Static Methods
 Static methods are similar to functions
in a procedural language.
 The class just provides a home for the
function.
 Recall Main()

Starting point for every C# program

No object
4747
Static Methods
Example:
class Math
{
public static double Sqrt(double d)
{
...
}
...
}
4848
Static Methods
To call a static method, you use the
class name rather than an object name.
Example:
double d = Math.Sqrt(42.24);
Note: If the class has any nonstatic fields, a
static method cannot refer to them.
49
Static Class
 A class that is intended to have only
static members can be declared static.
 The compiler will ensure that no
nonstatic members are ever added to
the class.
 Class cannot be instantiated.
 Math is a static class.
 Book says otherwise on page 138. According to the VS2008
documentation this is incorrect.
End of Section
50
Partial Classes
 In C#, a class definition can be divided
over multiple files.
 Helpful for large classes with many
methods.
 Used by Microsoft in some cases to
separate automatically generated code
from user written code.
 If class defintion is divided over multiple
files, each part is declared as a partial
class.
51
Partial Classes
In file circ1.cs
partial class Circle
{
// Part of class defintion
...
}
In file circ2.cs
partial class Circle
{
// Another part of class definition
...
}
5252
Summary
 A class consists of data declarations plus
functions that act on the data.
 Normally the data is private
 The public functions (or methods) determine
what clients can do with the data.
 An instance of a class is called an object.
 Objects have identity and lifetime.
 Like variables of built-in types.
5353
Summary
 Static members belong to the class as a
whole rather than to specific objects.
 variables
 methods
 const variables are automatically static
End of Presentation

More Related Content

What's hot

class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
Hoang Nguyen
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Programming in c++
Programming in c++Programming in c++
Programming in c++Baljit Saini
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
jehan1987
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
foreverredpb
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
Praveen M Jigajinni
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
Tushar Desarda
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 

What's hot (20)

class and objects
class and objectsclass and objects
class and objects
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 

Similar to Oops concept in c#

Object & classes
Object & classes Object & classes
Object & classes
Paresh Parmar
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
Mayank Jain
 
C++ classes
C++ classesC++ classes
C++ classes
Aayush Patel
 
Module 3 Class and Object.ppt
Module 3 Class and Object.pptModule 3 Class and Object.ppt
Module 3 Class and Object.ppt
RanjithKumar742256
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
VGaneshKarthikeyan
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
VGaneshKarthikeyan
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
aasuran
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
rajveer_Pannu
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
Ali Aminian
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
Hailsh
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
CS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptxCS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptx
ChetanChauhan203001
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-exampleDeepak Singh
 
C++ classes
C++ classesC++ classes
C++ classes
Zahid Tanveer
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
rsnyder3601
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
Rai University
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
Rai University
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 

Similar to Oops concept in c# (20)

Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Object & classes
Object & classes Object & classes
Object & classes
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes
C++ classesC++ classes
C++ classes
 
Module 3 Class and Object.ppt
Module 3 Class and Object.pptModule 3 Class and Object.ppt
Module 3 Class and Object.ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
CS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptxCS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptx
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
 
C++ classes
C++ classesC++ classes
C++ classes
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 

More from ANURAG SINGH

Microsoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentalsMicrosoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentals
ANURAG SINGH
 
Design thinkinga primer
Design thinkinga primerDesign thinkinga primer
Design thinkinga primer
ANURAG SINGH
 
Procurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables ChangesProcurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables Changes
ANURAG SINGH
 
Intro to data science
Intro to data scienceIntro to data science
Intro to data science
ANURAG SINGH
 
Unit testing Behaviour Driven Development
Unit testing Behaviour Driven DevelopmentUnit testing Behaviour Driven Development
Unit testing Behaviour Driven Development
ANURAG SINGH
 
Introduction To Data Science Using R
Introduction To Data Science Using RIntroduction To Data Science Using R
Introduction To Data Science Using R
ANURAG SINGH
 
Intro todatascience casestudyapproach
Intro todatascience casestudyapproachIntro todatascience casestudyapproach
Intro todatascience casestudyapproach
ANURAG SINGH
 
Introduction to ,NET Framework
Introduction to ,NET FrameworkIntroduction to ,NET Framework
Introduction to ,NET Framework
ANURAG SINGH
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
ANURAG SINGH
 

More from ANURAG SINGH (9)

Microsoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentalsMicrosoft Azure Cloud fundamentals
Microsoft Azure Cloud fundamentals
 
Design thinkinga primer
Design thinkinga primerDesign thinkinga primer
Design thinkinga primer
 
Procurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables ChangesProcurement Workflow in terms of SAP Tables Changes
Procurement Workflow in terms of SAP Tables Changes
 
Intro to data science
Intro to data scienceIntro to data science
Intro to data science
 
Unit testing Behaviour Driven Development
Unit testing Behaviour Driven DevelopmentUnit testing Behaviour Driven Development
Unit testing Behaviour Driven Development
 
Introduction To Data Science Using R
Introduction To Data Science Using RIntroduction To Data Science Using R
Introduction To Data Science Using R
 
Intro todatascience casestudyapproach
Intro todatascience casestudyapproachIntro todatascience casestudyapproach
Intro todatascience casestudyapproach
 
Introduction to ,NET Framework
Introduction to ,NET FrameworkIntroduction to ,NET Framework
Introduction to ,NET Framework
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 

Recently uploaded

Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 

Recently uploaded (20)

Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 

Oops concept in c#

  • 1. 11 Introduction to Object Oriented Programming in C# By Anurag Singh
  • 2. 22 Objectives You will be able to: 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create instances of a class. 4. Write and use class constructors. 5. Use the static keyword to create class members that are not associated with a particular object.
  • 3. 33 What is a class? Essentially a struct with built-in functions class Circle { double radius = 0.0; double Area() { return 3.141592 * radius * radius; } }
  • 4. 44 Encapsulation By default the class definition encapsulates, or hides, the data inside it. Key concept of object oriented programming. The outside world can see and use the data only by calling the build-in functions.  Called “methods”
  • 5. 55 Class Members Methods and variables declared inside a class are called members of that class.  Member variables are called fields.  Member functions are called methods. In order to be visible outside the class definition, a member must be declared public. As written in the previous example, neither the variable radius nor the method Area could be seen outside the class definition.
  • 6. 66 Making a Method Visible To make the Area() method visible outside we would write it as: public double Area() { return 3.141592 * radius * radius; } Unlike C++, we have to designate individual members as public. Not a block of members. We will keep the radius field private.
  • 7. 7 A Naming Convention  By convention, public methods and fields are named with the first letter capitalized.  Also class names.  Private methods and fields are named in all lower case.  This is just a convention.  It is not required, and it means nothing to the compiler.
  • 8. 88 Interface vs. Implementation  The public definitions comprise the interface for the class  A contract between the creator of the class and the users of the class.  Should never change.  Implementation is private  Users cannot see.  Users cannot have dependencies.  Can be changed without affecting users.
  • 9. 99 Creating Objects  The class definition does not allocate memory for its fields. (Except for static fields, which we will discuss later.)  To do so, we have to create an instance of the class. static void Main(string[ ] args) { Circle c; c = new Circle(); }
  • 10. 1010 Objects An instance of a class is called an object. You can create any number of instances of a given class.  Each has its own identity and lifetime.  Each has its own copy of the fields associated with the class. When you call a class method, you call it through a particular object. The method sees the data associated with that object.
  • 11. 1111 Using Classes and Objects  Classes and objects are used much like traditional types and variables:  Declare variables  Like pointers to structs  Circle c1;  Can be member variables in other classes  Assignment c2 = c1;  Function arguments picture1.crop(c1);
  • 12. 1212 Program Circle Demo  Demonstrate creating Program Circle in Visual Studio.  Demonstrate adding a class to a project  Students: Try this for yourself!
  • 13. 13 Create a New Project
  • 14. 14 Create a New Project
  • 16. 1616 Adding a Class to a Program  Each class definition should be a separate file.  In Visual Studio.  Project menu > Add Class  Use class name as file name.
  • 17. 17 Add a Class to the Project
  • 20. 20 Fill in Class Definition
  • 21. 21 Fill in Main() Call function Area() of Circle object c1
  • 23. 23 Program circle_demo in Action Area of Circle c1
  • 24. 2424 So far we have no way to set or change the value of radius of a Circle. We can use a constructor to set an initial value. A constructor is a method with the same name as the class. It is invoked when we call new to create an instance of a class. In C#, unlike C++, you must call new to create an object. Just declaring a variable of a class type does not create an object. Constructors
  • 25. 2525 A Constructor for Class Circle We can define a constructor for Circle so that it sets the value of radius. class Circle { private double radius; ... public Circle (double r) { radius = r; } ... } Note: Constructors have no return type.
  • 28. 2828 Multiple Constructors A class can have any number of constructors. All must have different signatures. (The pattern of types used as arguments.) This is called overloading a method. Applies to all methods in C#. Not just constructors. Different names for arguments don’t matter, Only the types.
  • 29. 2929 Default Constructor If you don’t write a constructor for a class, the compiler creates a default constructor. The default constructor is public and has no arguments. c = new Circle(); The default constructor sets numeric variables to zero and Boolean fields to false. In constructors that you write, the same is true for any variables that you don’t initialize.
  • 30. 3030 Creating multiple objects of the same type
  • 32. 3232 Good Programming Practice  All member variables should be private.  except const variables  Users of the class can use them and manipulate them only by invoking the public methods of the class.  Only way for users to do anything with an object.
  • 33. 3333 Class Circle  Let's extend class Circle by providing names for circle objects.  Also provide accessor functions  Public functions that let the outside world access attributes of an object.
  • 34. 34 Class Circle New member New constructor Accessor Methods
  • 35. 3535 Getting User Input  What if we want the user to specify the radius of a Circle at run time?  Could overload the constructor and provide a version that asks for input.  Better to provide a separate function outside the class definition.  Separate User Interface from class logic.  Let’s write a function that asks the user for a name and a radius and creates a Circle of that radius with that name.
  • 36. 3636 Getting User Input static Circle Create_Circle() { String name, temp; double radius; Console.Write("Please enter name for new Circle: "); name = Console.ReadLine(); Console.Write("Please enter radius: "); temp = Console.ReadLine(); radius = double.Parse(temp); return new Circle(name, radius); } In class Program (along with Main() )
  • 37. 37 Main() static void Main(string[] args) { Circle c1 = Create_Circle(); Console.Write("Circle " + c1.Name()); Console.WriteLine(" created with radius " + c1.Radius()); Console.WriteLine("Its area is " + c1.Area()); Console.ReadLine(); // Keep window open. }
  • 39. 3939 Passing Objects to a Function  Let's extend class Circle with a method to compare one Circle to another.  In class Circle ... public bool Is_Greater_Than(Circle other) { if (this.Radius() > other.Radius()) { return true; } else { return false; } } Note keyword "this" Call Radius() in Circle object passed as argument.
  • 40. 4040 Using "Is_Greater_Than" Method static void Main(string[] args) { Circle Circle_A = Create_Circle(); Console.Write ("Circle " + Circle_A.Name() ); Console.WriteLine (" created with radius " + Circle_A.Radius()); Console.WriteLine ("Its area is " + Circle_A.Area()); Circle c2= Create_Circle(); Console.Write ("Circle " + c2.Name() ); Console.WriteLine (" created with radius " + c2.Radius()); Console.WriteLine ("Its area is " + c2.Area());
  • 41. 4141 Using "Is_Greater_Than" Method if (c1.Is_Greater_Than(c2)) { Console.Write ("Circle " + c1.Name() + " is greater than "); Console.WriteLine( "Circle " + c2.Name()); } else if (c2.Is_Greater_Than(c1)) { Console.Write ("Circle " + c2.Name() + " is greater than "); Console.WriteLine( "Circle " + c1.Name()); } else { Console.Write("Circle " + c1.Name() + " and Circle " + c2.Name()); Console.WriteLine (" are the same size."); }
  • 43. 4343 Static Fields Sometimes we need a single variable that is shared by all members of a class. Declare the field static. You can also declare a field const in order to ensure that it cannot be changed. Not declared static – but is a static variable  There is only one instance
  • 44. 4444 Static Fields class Math { ... public const double PI = 3.14159265358979; } In class Circle -- public double Area() { return Math.PI * radius * radius; } Class name rather than object name.
  • 45. 4545 Static Methods  Sometimes you want a method to be independent of a particular object.  Consider class Math, which provides functions such as Sin, Cos, Sqrt, etc.  These functions don’t need any data from class Math. They just operate on values passed as arguments. So there is no reason to instantiate an object of class Math.
  • 46. 4646 Static Methods  Static methods are similar to functions in a procedural language.  The class just provides a home for the function.  Recall Main()  Starting point for every C# program  No object
  • 47. 4747 Static Methods Example: class Math { public static double Sqrt(double d) { ... } ... }
  • 48. 4848 Static Methods To call a static method, you use the class name rather than an object name. Example: double d = Math.Sqrt(42.24); Note: If the class has any nonstatic fields, a static method cannot refer to them.
  • 49. 49 Static Class  A class that is intended to have only static members can be declared static.  The compiler will ensure that no nonstatic members are ever added to the class.  Class cannot be instantiated.  Math is a static class.  Book says otherwise on page 138. According to the VS2008 documentation this is incorrect. End of Section
  • 50. 50 Partial Classes  In C#, a class definition can be divided over multiple files.  Helpful for large classes with many methods.  Used by Microsoft in some cases to separate automatically generated code from user written code.  If class defintion is divided over multiple files, each part is declared as a partial class.
  • 51. 51 Partial Classes In file circ1.cs partial class Circle { // Part of class defintion ... } In file circ2.cs partial class Circle { // Another part of class definition ... }
  • 52. 5252 Summary  A class consists of data declarations plus functions that act on the data.  Normally the data is private  The public functions (or methods) determine what clients can do with the data.  An instance of a class is called an object.  Objects have identity and lifetime.  Like variables of built-in types.
  • 53. 5353 Summary  Static members belong to the class as a whole rather than to specific objects.  variables  methods  const variables are automatically static End of Presentation