0% found this document useful (0 votes)
82 views45 pages

Lecture 2 - C# Class - Method

The document discusses object-oriented programming concepts in C#, including classes, objects, methods, and parameters. It defines classes as templates that define an object's properties and behaviors. Objects are instantiated from classes and contain field values and expose behaviors through methods. Methods implement an object's behaviors and can take parameters. The document provides examples of defining classes, creating objects, defining and calling methods, and using parameters and arguments.

Uploaded by

Bob Long
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
82 views45 pages

Lecture 2 - C# Class - Method

The document discusses object-oriented programming concepts in C#, including classes, objects, methods, and parameters. It defines classes as templates that define an object's properties and behaviors. Objects are instantiated from classes and contain field values and expose behaviors through methods. Methods implement an object's behaviors and can take parameters. The document provides examples of defining classes, creating objects, defining and calling methods, and using parameters and arguments.

Uploaded by

Bob Long
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 45

Class - Method

Content
Explain classes and objects
Define and describe methods
List the access modifiers
Explain method overloading
Define and describe constructors and destructors
Object-Oriented Programming
Programming languages are based on two fundamental concepts, data and
ways to manipulate data.
Traditional languages such as Pascal and C used the procedural approach
which focused more on ways to manipulate data rather than on the data itself.
This approach had several drawbacks such as lack of re-use and lack of
maintainability.
To overcome these difficulties, OOP was introduced, which focused on data
rather than the ways to manipulate data.
The object-oriented approach defines objects as entities having a defined set
of values and a defined set of operations that can be performed on these
values.
Features
Object-oriented programming provides the following features:
• Abstraction is the feature of extracting only the required information from

Abstraction objects. For example, consider a television as an object. It has a manual stating
how to use the television. However, this manual does not show all the technical
details of the television, thus, giving only an abstraction to the user.

• Details of what a class contains need not be visible to other classes and objects

Encapsulation that use it. Instead, only specific information can be made visible and the others
can be hidden. This is achieved through encapsulation, also called data hiding.
Both abstraction and encapsulation are complementary to each other.

• Inheritance is the process of creating a new class based on the attributes and
methods of an existing class. The existing class is called the base class whereas the
Inheritance new class created is called the derived class. This is a very important concept of
object-oriented programming as it helps to reuse the inherited attributes and
methods.

• Polymorphism is the ability to behave differently in different situations. It is


Polymorphism basically seen in programs where you have multiple methods declared with the
same name but with different parameters and different behavior.
Classes and Objects
C# programs are composed of classes that represent the entities of the program which
also include code to instantiate the classes as objects.
When the program runs, objects are created for the classes and they may interact with
each other to provide the functionalities of the program.
An object is a tangible entity such as a car, a table, or a briefcase. Every object has some
characteristics and is capable of performing certain actions.
The concept of objects in the real world can also be extended to the programming
world. An object in a programming language has a unique identity, state, and behavior.
The state of the object refers to its characteristics or attributes whereas the behavior of
the object comprises its actions.
An object has various features that can describe it which could be the company name,
model, price, mileage, and so on.
Classes and Objects
The following figure shows an example of objects:

An object stores its identity and state in fields (also called variables)
and exposes its behavior through methods.
Class
Several objects have a common state and behavior and thus, can be
grouped under a single class.
Example
Creating Classes
The concept of classes in the real world can be extended to the programming world,
similar to the concept of objects.
In object-oriented programming languages like C#, a class is a template or blueprint
which defines the state and behavior of all objects belonging to that class.
A class comprises fields, properties, methods, and so on, collectively called data
members of the class. In C#, the class declaration starts with the class keyword
followed by the name of the class. 
The following syntax is used to declare a class:
public class ClassName
{
 // class member
}
Creating Classes - example
Guidelines for Naming Classes
There are certain conventions to be followed for class names while
creating a class that help you to follow a standard for naming classes.
These conventions state that a class name:
Should be a noun and written in initial caps, and not in
mixed case.

Should be simple, descriptive, and meaningful.

Cannot be a C# keyword.

Cannot begin with a digit but can begin with the ‘@’
character or an underscore (_).

Example:
Valid class names are: Account, @Account, and _Account.
 Invalid class names are: 2account, class, Acccount, and Account123.
Instantiating Objects
It is necessary to create an object of the class to access the variables and
methods defined within it.
In C#, an object is instantiated using the new keyword. On
encountering the new keyword, the Just-in-Time (JIT) compiler
allocates memory for the object and returns a reference of that allocated
memory.
The following syntax is used to instantiate an object.
Syntax:
<ClassName> <objectName> = new <ClassName>();
Example
Methods
Methods are functions declared in a class and may be used to perform operations on
class variables.
They are blocks of code that can take parameters and may or may not return a value.
A method implements the behavior of an object, which can be accessed by
instantiating the object of the class in which it is defined and then invoking the
method.
Methods specify the manner in which a particular operation is to be carried out on
the required data members of the class.
Example:
The class Car can have a method Brake()that represents the ’Apply Brake’ action.
To perform the action, the method Brake()will have to be invoked by an object of class
Car.
Creating Methods
Conventions to be followed for naming methods state that a method name:

Cannot be a C# keyword, cannot contain spaces,


and cannot begin with a digit

Can begin with a letter, underscore, or the “@”


character

Some examples of valid method names are:


Add(), Sum_Add(), and @Add().

Syntax:
 <access_modifier> <return_type> <MethodName> ([ list of parameters])
{
 // body of method
}
Example
The following code shows the definition of a method named Add() that
adds two integer numbers:
using System;
class Sum
{
int Add(int numOne, int numTwo)
{
int addResult = numOne + numTwo;
Console.WriteLine(“Addition = “ + addResult);
. . .
}
}

 
Invoking Methods
A method can be invoked in a class by creating
an object of the class where the object name is
followed by a period (.) and the name of the
method followed by parentheses.
In C#, a method is always invoked from another
method. This is referred to as the calling method
and the invoked method is referred to as the
called method.
The following figure displays how a method
invocation or call is stored in the stack in
memory and how a method body is defined:
Example
class Book{
string _bookName;
public string Print() {
return _bookName;
}
public void Input(string bkName) {
_bookName = bkName;
}
static void Main(string[] args)
{
Book objBook = new Book();
objBook.Input(“C#-The Complete Reference”);
Console.WriteLine(objBook.Print());
}
}
Method Parameters and Arguments
Method parameters and arguments:
• The variables included in a method definition are
called parameters. Which may have zero or more
parameters, enclosed in parentheses and separated
Parameters by commas. If the method takes no parameters, it is
indicated by empty parentheses.

• When the method is called, the data that you send into
Arguments the method's parameters are called arguments.

The following figure shows an example of


parameters and arguments:
Named Arguments
A method in a C# program can accept multiple arguments that are
passed based on the position of the parameters in the method signature.
A method caller can explicitly name one or more arguments being
passed to the method instead of passing the arguments based on their
position.
An argument passed by its name instead of its position is called a named
argument.
While passing named arguments, the order of the arguments declared in
the method does not matter.
Named arguments are beneficial because you do not have to remember
the exact order of parameters in the parameter list of methods.
Example
using System;
class Student
{
voidprintName(String firstName, String lastName)
{
Console.WriteLine("First Name = {0}, Last Name = {1}", firstName, lastName);
}
static void Main(string[] args)
{
Student student = new Student();
/*Passing argument by position*/
student.printName("Henry","Parker");
/*Passing named argument*/
student.printName(firstName: "Henry", lastName: "Parker");
student.printName(lastName: "Parker", firstName: "Henry");
/*Passing named argument after positional argument*/
student.printName("Henry", lastName: "Parker");
  }
}
Optional Arguments
C# supports optional arguments in methods and can be emitted by the
method caller.
Each optional argument has a default value.
using System;
Class OptionalParameterExample
{
void printMessage(String message="Hello user!") {
Console.WriteLine("{0}", message);
}
static void Main(string[] args) {
OptionalParameterExample opExample = new OptionalParameterExample();
opExample.printMessage("Welcome User!");
opExample.printMessage();
}
}
Static Classes
Classes that cannot be instantiated or inherited are known as classes and the static
keyword is used before the class name that consists of static data members and static
methods.
It is not possible to create an instance of a static class using the new keyword. The main
features of static classes are as follows:
They can only contain static members.
They cannot be instantiated or inherited and cannot contain instance constructors. However,
the developer can create static constructors to initialize the static members.
The code creates a static class Product having static variables _productId and price, and
a static method called Display().
It also defines a constructor Product() which initializes the class variables to 10 and
156.32 respectively.
Since there is no need to create objects of the static class to call the required methods,
the implementation of the program is simpler and faster than programs containing
instance classes.
Example
Static Methods
A method is called using an object of the class but it is possible for a method to
be called without creating any objects of the class by declaring a method as static.
A static method is declared using the static keyword. For example, the
Main()method is a static method and it does not require any instance of the class
for it to be invoked.
A static method can directly refer only to static variables and other static
methods of the class but can refer to non-static methods and variables by using
an instance of the class.
The following syntax is used to create a static method:
static <return_type> <MethodName>()
{
 // body of the method
}
Example
using System;
class Calculate The following figure displays invoking
{ a static method:
public static void Addition(int val1, int val2)
{
Console.WriteLine(val1 + val2);
}
public void Multiply(int val1, int val2)
{
Console.WriteLine(val1 * val2);
}
}
classStaticMethods
{
static void Main(string [] args)
{
Calculate.Addition(10, 50);
Calculate objCal = new Calculate();
objCal.Multiply(10, 20);
}
}
Static Variables
In addition to static methods, you can also have static variables in C#.
A static variable is a special variable that is accessed without using an
object of a class.
A variable is declared as static using the static keyword. When a static
variable is created, it is automatically initialized before it is accessed.
Only one copy of a static variable is shared by all the objects of the
class.
Therefore, a change in the value of such a variable is reflected by all the
objects of the class.
An instance of a class cannot access static variables. Figure 6.8 displays
the static variables.
Example
Access Modifiers
C# provides you with access modifiers that allow you to specify which
classes can access the data members of a particular class.
In C#, there are four commonly used access modifiers.

public private protected internal


The various accessibility levels
Method Overloading in C#
In object-oriented programming, every method has a signature which
includes:
Method Overloading in C#
The following figure displays the concept of method overloading using
an example:
Example
using System;
classMethodOverloadExample
{
static void Main(string[] args)
{
Console.WriteLine(“Square of integer value “ + Square(5));
Console.WriteLine(“Square of float value “ + Square(2.5F));
}
staticint Square(intnum)
{
returnnum * num;
}
static float Square(float num)
{
returnnum * num;
}
}
Guidelines and Restrictions
Guidelines to be followed while overloading methods in a program, to
ensure that the overloaded methods function accurately are as follows:
Constructors and Destructors
A C# class can define constructors and destructors as follows:
Constructors
Constructors can initialize the variables of a class or perform startup
operations only once when the object of the class is instantiated.
They are automatically executed whenever an instance of a class is
created.
The following figure shows the constructor declaration:
Constructors
It is possible to specify the accessibility level of constructors within an
application by using access modifiers such as:
public: Specifies that the constructor will be called whenever a class is
instantiated. This instantiation can be done from anywhere and from any
assembly.
private: Specifies that this constructor cannot be invoked by an instance of
a class.
protected: Specifies that the base class will initialize on its own whenever
its derived classes are created. Here, the class object can only be created in
the derived classes.
internal: Specifies that the constructor has its access limited to the current
assembly. It cannot be accessed outside the assembly.
Example
using System;
public class Circle
{
private Circle()
{
}
}
class CircleDetails
{
public static void Main(string[] args)
{
Circle objCircle = new Circle();
}
}
Example
using System;
class Employees
{
string _empName;
int _empAge;
string _deptName;
Employees(string name, int num)
{
_empName = name;
_empAge = num;
_deptName = “Research & Development”;
}
static void Main(string[] args)
{
Employees objEmp = new Employees(“John”, 10);
Console.WriteLine(objEmp._deptName);
}
}
Default and Static Constructors
Static constructor
Syntax
Constructor Overloading
Declaring more than one constructor in a class is called constructor
overloading.
The process of overloading constructors is similar to overloading methods
where every constructor has a signature similar to that of a method.
Multiple constructors in a class can be declared wherein each constructor
will have different signatures.
Constructor overloading is used when different objects of the class might
want to use different initialized values.
Overloaded constructors reduce the task of assigning different values to
member variables each time when needed by different objects of the class.
using System;

Example
public class Rectangle {
double _length;
double _breadth;
public Rectangle() {
_length = 13.5;
_breadth = 20.5;
}
public Rectangle(double len, double wide) {
_length = len;
_breadth = wide;
}
public double Area() {
return _length * _breadth;
}
static void Main(string[] args) {
Rectangle objRect1 = new Rectangle();
Console.WriteLine(“Area of rectangle = “ + objRect1.Area());
Rectangle objRect2 = new Rectangle(2.5, 6.9);
Console.WriteLine(“Area of rectangle = “ + objRect2.Area());
}
}
Destructors
A destructor is a special method which has the same name as the class
but starts with the character ~ before the class name and immediately
de-allocate memory of objects that are no longer required. Following
are the features of destructors:
Destructors cannot be overloaded or inherited.
Destructors cannot be explicitly invoked.
Destructors cannot specify access modifiers and cannot take parameters.
Example
class Employee {
string name;
public Employee() {}
public Employee(string name) {
this.name = name;
}
~Employee() {
Console.WriteLine(“Destructor runs.”);
}
}

You might also like