0% found this document useful (0 votes)
109 views73 pages

C# Slides Part 3

Classes are templates that define the characteristics of objects. An object is an instance of a class that inherits its properties and methods. Classes contain fields to store data and methods to perform actions. Constructors initialize new objects by assigning values to fields. Properties provide a way to access private fields through public get and set accessors, hiding implementation details while enabling value access.

Uploaded by

prashant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views73 pages

C# Slides Part 3

Classes are templates that define the characteristics of objects. An object is an instance of a class that inherits its properties and methods. Classes contain fields to store data and methods to perform actions. Constructors initialize new objects by assigning values to fields. Properties provide a way to access private fields through public get and set accessors, hiding implementation details while enabling value access.

Uploaded by

prashant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

C# Classes & Objects

C# Classes & Objects


What are Classes and Objects?
Classes and objects are the two main aspects of OOP

Class Object
Fruit Apple, Banana, Mango
Car Volvo, Audi, Toyota

• A class is a template for objects, and an object is an instance


of a class
• When the individual objects are created, they inherit all the
variables and methods from the class
• A Class is a "blueprint" for creating objects
C# Classes & Objects
Classes are declared by using the class keyword followed by a
unique identifier

//[access modifier] - [class] - [identifier]


public class Customer
{
// Fields, properties, methods and events go here...
}
C# Classes & Objects
public class Car
{
public string colour = "red";
}
• When a variable is declared directly in a class, it is often
referred to as a field (or attribute).

• It is not required, but it is a good practice to start with an


uppercase first letter when naming classes. Also, it is
common that the name of the C# file and the class matches,
as it makes our code organized. However it is not required
(like in Java).
C# Classes & Objects
a class is a reference type

At run time, when you declare a variable of a reference type,


the variable contains the value null until you explicitly create an
instance of the class by using the new operator,

or assign it an object of a compatible type that may have been


created elsewhere
//Declaring an object of type MyClass.
MyClass mc = new MyClass();
//Declaring another object of the same type, assigning it value
//of the first object.
MyClass mc2 = mc;
C# Classes & Objects
A class defines a type of object, but it is not an object itself

An object is a concrete entity based on a class, and is sometim


es referred to as an instance of a class

Objects can be created by using the new keyword followed by


the name of the class that the object will be based on

Customer object1 = new Customer();


C# Classes & Objects
When an instance of a class is created, a reference to the
object is passed back to the programmer

object1 is a reference to an object that is based on Customer

Reference refers to the new object but does not contain the
object data itself

You can create an object reference without creating an object


at all

Customer object2;
C# Classes & Objects
Creating object references that don't refer to an object will fail
at run time on access that object

A reference can be made to refer to an object, either by


creating a new object, or by assigning it an existing object

Customer object3 = new Customer();


Customer object4 = object3;

object 3 and object4 both refer to the same object

Any changes to the object made through object3 are reflected


in subsequent uses of object4
C# Classes & Objects
You can create multiple objects of one class
//Class Car
public class Car
{
public string colour = "red";
}

// Program.cs
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.colour);
Console.WriteLine(myObj2.colour);
C# Classes & Objects
Using Multiple Classes
• You can also create an object of a class and access it in
another class
• This is often used for better organization of classes. One
class has all the fields and methods, while the other class
holds the Main()method (code to be executed)

prog2.cs
public class Car { public string color = "red"; }

prog.cs
Car myObj = new Car();
Console.WriteLine(myObj.color);
C# Class Members
Fields and methods inside classes are often referred to as
"Class Members"

Car class with three class members: 2 x fields and 1 x method


// The class
class Car
{
// Class members
string colour = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{ Console.WriteLine("The car is going as fast as it can!"); }
}
C# Class Members
The fields can be left blank, and can be modified when creating
the object
//Car.cs
public class Car
{ public string color;
public int maxSpeed; }

//Program.cs
Car myObj = new Car();
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
C# Constructors
A constructor is a special method that is called when an object
of a class is created and is used to initialize objects
//Car.cs
class Car // Create a Car class
{ public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{ model = "Mustang"; // Set the initial value for model } }

//Program.cs
Car Ford = new Car(); // this will call the constructor
Console.WriteLine(Ford.model); // Print the value of model
// Outputs "Mustang"
C# Constructors
Constructor name must match the class name, it cannot have
a return type (like void or int)

The constructor is called when the object is created

All classes have constructors by default, if you do not create a


class constructor yourself, C# creates one for you. However,
then you are not able to set initial values for fields

Constructors can also take parameters, which is used to


initialize fields, similar to the way we pass parameters to
methods
Constructors can be overloaded like methods
C# Constructors
//Car.cs
class Car
{
public string model;
// Create a class constructor with a parameter
public Car (string modelName)
{
model = modelName;
}
}

//Program.cs
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model); // Outputs "Mustang"
C# Constructors
class Car
{
public string model;
public string color;
public int year;
// Create a class constructor with multiple parameters
public Car(string modelName, string modelColor, int modelYear)
{
model = modelName;
color = modelColor;
year = modelYear;
}}
-------------------------
Car Ford = new Car("Mustang", "Red", 1969);
Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
// Outputs Red 1969 Mustang
C# Properties
Before understanding properties, you should have a basic
understanding of "Encapsulation"

The meaning of Encapsulation, is to make sure that "sensitive"


data is hidden from users. To achieve this, you must –

• declare fields/variables as private

• provide public get and set methods, through properties,


to access and update the value of a private field
C# Properties
Private variables can only be accessed within the same class
(an outside class has no access to it)

However, sometimes we need to access them - and it can be


done with properties

A property is like a combination of a variable and a method,


and it has two methods: a get and a set method
C# Properties
class Person
{ private string name; // field
public string Name // property
{
get
{
return name;
} // get method
set
{
name = value; //value is a keyword
} // set method
}}
C# Properties
The Name property is associated with the name field. It is a
good practice to use the same name for both the property and
the private field, but with an uppercase first letter.

The get method returns the value of the variable name.

The set method assigns a value to the name variable.


The value keyword represents the value we assign to the
property.

Now we can use the Name property to access and update


the private field of the Person class.
C# Properties
class Person
{ private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
------------------------------ //Program.cs
Person myObj = new Person();
myObj.Name = ”Laxman";
Console.WriteLine(myObj.Name); //The output will be Laxman
C# Properties
Automatic Properties (Short Hand)
C# also provides a way to use short-hand / automatic
properties, where you do not have to define the field for the
property, and you only have to write get; and set; inside the
property.
class Person {
public string Name // property
{ get; set; } }
-------------------------------------------------------
Person myObj = new Person();
myObj.Name = ”Laxman";
Console.WriteLine(myObj.Name);
//The output will be Laxman
C# Properties
A property is a member that provides a flexible mechanism to
read, write, or compute the value of a private field (backing
field)

Properties can be used as if they are public data members, but


they are actually special methods called accessors

This enables data to be accessed easily and still helps promote


the safety and flexibility of methods
C# Properties
Properties enable a class to expose a public way of getting and
setting values, while hiding implementation or verification code

A get property accessor is used to return the property value,


and a set property accessor is used to assign a new value

In C# 9 and later, an init property accessor is used to assign a


new value only during object construction

The value keyword is used to define the value being assigned


by the set or init accessor
C# Properties
Properties can be
ü read-write (they have both a get and a set accessor),
ü read-only(they have a get accessor but no set accessor), or
ü write-only (they have a set accessor, but no get accessor)

Write-only properties are rare and are most commonly used to


restrict access to sensitive data

Simple properties that require no custom accessor code can be


implemented either as expression body definitions or as auto-
implemented properties
C# Properties
class TimePeriod
{
private double _seconds; //backing field
public double Hours //property.
{ get { return _seconds / 3600; } //=> _seconds / 3600;
set {
if (value < 0 || value > 24)
throw new ArgumentOutOfRangeException(
$"{nameof(value)} must be between 0 and 24.");
_seconds = value * 3600;
//=> _seconds = value * 3600; when simple set, NA here.
} } }
C# Properties
//Program.cs
TimePeriod t = new TimePeriod();
// Property assignment causes the 'set' accessor to be called.
t.Hours = 24;

// Retrieving the property causes the 'get' accessor to be called.


Console.WriteLine($"Time in hours: {t.Hours}");

// The example displays the following output:


// Time in hours: 24
C# Object Initializer
C# Object Initializer
C# lets you instantiate an object or collection and perform
member assignments in a single statement >>

Object initializers let you assign values to any accessible fields


or properties of an object at creation time without having to
invoke a constructor followed by lines of assignment
statements

Object initializer syntax enables you to specify arguments for a


constructor or omit the arguments (and parentheses syntax)

Object initializers syntax allows you to create an instance, and


after that it assigns the newly created object, with its assigned
properties, to the variable in the assignment
C# Object Initializer
public class Cat //Program.cs
{ Cat cat1 = new Cat();
// Auto-implemented properties. Cat cat2 = new Cat(“Fluffy”);
public int Age { get; set; } Cat cat3 = new Cat(“Tuffy”, 10);
public string Name { get; set; }

//Constructor. Cat Mycat = new Cat


public Cat() { Age = 10, Name = "Fluffy" };
{ }
public Cat(string name) Cat AnotherCat = new Cat("Fluffy")
{ this.Name = name; } { Age = 10 };
public Cat (string nm, int ag)
{ Name = nm; Age = ag; }
}
Reading Assignment #2

The C# type system

https://docs.microsoft.com/en-
us/dotnet/csharp/fundamentals/types/
C# Inheritance
C# Inheritance
In C#, it is possible to inherit fields and methods from one class
to another. We group the "inheritance concept" into two
categories
• Derived Class (child) - the class that inherits from another
class
• Base Class (parent) - the class being inherited from

To inherit from a class, use the : symbol

Why And When To Use "Inheritance"?


• It is useful for code reusability: reuse fields and methods of
an existing class when you create a new class
C# Inheritance
Classes fully support inheritance

When a class is created, you can inherit from any other class
that is not defined as sealed, and other classes can inherit from
your class and override class virtual methods

Furthermore, you can implement one or more interfaces

Inheritance is accomplished by using a derivation, which


means a class is declared by using a base class from which it
inherits data and behaviour
C# Inheritance
public class Manager : Employee
{
// Employee fields, properties, methods and events are
// inherited

// New Manager fields, properties, methods and events go


// here...
}

When a class declares a base class, it inherits all the members


of the base class except the constructors
C# Inheritance
A class in C# can only directly inherit from one base class

However, because a base class may itself inherit from another


class, a class may indirectly inherit multiple base classes

Furthermore, a class can directly implement one or more


interfaces

A sealed class does not allow other classes to derive from it

If ClassC is derived from ClassB, and ClassB is derived


from ClassA, ClassC inherits the members declared
in ClassB and ClassA
C# Inheritance
class Vehicle // base class (parent) // Create a myCar object
{ Car myCar = new Car();
public string brand = "Ford";
// Vehicle field // Call the honk() method (From the
Vehicle class) on the myCar object
public void honk() // Vehicle method
{ myCar.honk();
Console.WriteLine("Tuut, tuut!");
} // Display the value of the brand field
} (from the Vehicle class) and the
value of the modelName from the
Car class
class Car : Vehicle
// derived class (child) Console.WriteLine(myCar.brand + "
{ " + myCar.modelName);
public string modelName = "Mustang";
// Car field }
C# Inheritance
The sealed keyword
• If you don't want other classes to inherit from a class, use
the sealed keyword:
• If you try to access a sealed class, C# will generate an error:

sealed class Vehicle { ... }

class Car : Vehicle { ... }

The error message will be something like this:


'Car': cannot derive from sealed type 'Vehicle'
C# Inheritance
Inheritance lets us inherit fields and methods from another
class

Polymorphism uses those methods to perform different tasks.


This allows us to perform a single action in different ways

E.g. a base class called Animal has a method


called animalSound(), derived classes of Animals could be
Pigs, Cats, Dogs, Birds - and they also have their own
implementation of an animal sound (the pig oinks, and the cat
meows, etc.)
C# Inheritance
class Animal // Base class (parent)
{
public virtual void animalSound()
{ Console.WriteLine("The animal makes a sound"); }}

class Pig : Animal // Derived class (child)


{
public override void animalSound()
{ Console.WriteLine("The pig says: wee wee"); }}

class Dog : Animal // Derived class (child)


{
public override void animalSound()
{ Console.WriteLine("The dog says: bow wow"); }}
C# Access Modifiers
C# Access Modifiers
All types and type members have an accessibility level

The accessibility level controls whether they can be used from


other code in your assembly or other assemblies

An assembly is a .dll or .exe created by compiling one or


more .cs files in a single compilation
C# Access Modifiers
To set the access level/visibility for classes, fields, methods and
properties
Modifier Description
public The type or member can be accessed by any other code in the same
assembly or another assembly that references it
private The type or member can be accessed only by code in the
same class or struct
protected The type or member can be accessed only by code in the same class,
or in a class that is derived from that class
internal The type or member can be accessed by any code in the same
assembly, but not from another assembly, i.e., internal types or
members can be accessed from code that is part of the same
compilation

Access Modifiers
C# Abstract Classes
C# Abstract Classes
A class can be declared abstract

An abstract class contains abstract methods that have a


signature definition but no implementation

Abstract classes cannot be instantiated, they can only be used


through derived classes that implement the abstract methods

abstract keyword enables you to create classes


and class members that are incomplete and must be
implemented in a derived class
C# Abstract Classes
Purpose of an abstract class is to provide a common definition
of a base class that multiple derived classes can share

E.g., a class library may define an abstract class that is used as


a parameter to many of its functions, and require programmers
using that library to provide their own implementation of the
class by creating a derived class

public abstract class A


{
// Class members here.
}
C# Abstract Classes
Abstract method: can only be used in an abstract class, and it
does not have a body

The body of an abstract method is provided by the derived


class (inherited from)

public abstract class A


{
public abstract void DoWork(int i);
}

An abstract class can have both abstract and regular methods


C# Abstract Classes
Abstract methods have no implementation, so the method
definition is followed by a semicolon instead of a normal
method block

Derived classes of the abstract class must implement all


abstract methods
C# Abstract Classes
abstract class Shape //Program.cs
{ public abstract int Square sq = new Square(12);
GetArea(); }
Console.WriteLine($"Area of
class Square : Shape the square = {sq.GetArea()}");
{ // Output: Area of the square =
private int _side; 144
public Square(int n) {
_side = n; }
// GetArea method required to
avoid a compile-time error.
public override int GetArea() {
return _side * _side; } }
C# Sealed Keyword
The sealed keyword enables you to prevent the inheritance of a
class or certain class members that were previously
marked virtual

Classes can be declared as sealed by putting the


keyword sealed before the class definition

public sealed class D


{ // Class members here. }
C# Sealed Class
A sealed class cannot be used as a base class, for this reason,
it cannot also be an abstract class

Sealed classes prevent derivation, because they can never be


used as a base class, some run-time optimizations can make
calling sealed class members slightly faster

public sealed class D


{
// Class members.
}
C# Sealed Class
A method, indexer, property, or event, on a derived class that is
overriding a virtual member of the base class can declare that
member as sealed, which negates the virtual aspect of the
member for any further derived class

Put sealed keyword before the override keyword in the class


member declaration

public class D : C
{
public sealed override void DoWork() { }
}
C# Abstract Classes
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
//Not possible to create an object of the Animal class
Animal myObj = new Animal();

//Will generate an error (Cannot create an instance of the


abstract class or interface 'Animal’)
C# Abstract Classes
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();

// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
C# Abstract Classes
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
------------------------------------------------------------------------
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
C# Interfaces
C# Interfaces
Another way to achieve abstraction in C#, is with interfaces.

An interface is a completely "abstract class", which can only


contain abstract methods and properties (with empty bodies):

// interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
C# Interfaces
It is considered good practice to start with the letter "I" at the
beginning of an interface, as it makes it easier for yourself and
others to remember that it is an interface and not a class

By default, members of an interface are abstract and public

Interfaces can contain properties and methods, but not fields


C# Interfaces
To access the interface methods, the interface must be
"implemented" by another class

To implement an interface, use the : symbol (just like with


inheritance)

The body of the interface method is provided by the


"implement" class

You do not have to use the override keyword when


implementing an interface
C# Interfaces
// Interface //Program.cs
interface IAnimal Pig myPig = new Pig();
{
void animalSound(); // Create a Pig object
// interface method (does not have a myPig.animalSound();
body)
}
// Pig implements the IAnimal
interface
class Pig : IAnimal
{
public void animalSound()
{ // body of animalSound() is
provided here.
Console.WriteLine("The pig
says: wee wee"); }}
C# Interfaces
Like abstract classes, interfaces cannot be used to create
objects (in the example above, it is not possible to create an
"IAnimal" object in the Program class)

Interface methods do not have a body - the body is provided by


the "implement" class

Interfaces can contain properties and methods, but not


fields/variables

Interface members are by default abstract and public

An interface cannot contain a constructor (as it cannot be used


to create objects)
C# Interfaces
Why And When To Use Interfaces?

To achieve security - hide certain details and only show the


important details of an object (interface)

C# does not support "multiple inheritance" (a class can only


inherit from one base class), it can be achieved with interfaces,
because the class can implement multiple interfaces

To implement multiple interfaces, separate them with a comma


C# Interfaces
interface IFirstInterface { void myMethod(); // interface method }

interface ISecondInterface { void myOtherMethod(); // interface method }

// Implement multiple interfaces


class DemoClass : IFirstInterface, ISecondInterface
{
public void myMethod()
{ Console.WriteLine("Some text.."); }
public void myOtherMethod()
{ Console.WriteLine("Some other text..."); }}
-------------------------------------------------------------------------------------------
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
C# OOP PRACTICE

OOP Practice
C# OOP PRACTICE

OOP Exercises
C# OOP PRACTICE
Ex 1
Create a C# program that requests three names of people from the user Input
and stores them in an array of objects of type Person. To do this, first Jana
Sara
create a Person class that has a Name property of type string and
Chaitanya
override the ToString() method.
End the program by reading people and executing the ToString() method Output
on the screen. Hello! My name is
Jana
Hello! My name is
Sara
Hello! My name is
Chaitanya
C# OOP PRACTICE
Ex 2
Create a new C # project with three classes plus another class to test the logic in Input
your code. The main classes of the program are the following classes:
• Person
• Student
Output
• Professor
Hello!
The Student and Teacher classes inherit from the Person class. The Student class Hello!
will include a public Study() method that will write I'm studying on the screen. The My age is 21 years
Person class must have two public methods Greet() and SetAge(int age) that will old
assign the age of the person. The Teacher class will include a I'm studying
public Explain() method that will write I'm explaining on the screen. Also create a Hello!
public method ShowAge() in the Student class that writes My age is: x years old on I'm explaining
the screen.
In Program.cs do the following:
• Create a new Person and make him say hello
• Create a new Student, set an age, say hello, displays his/ her age and starts
studying.
• Create a new Teacher, set an age, say hello and start the explanation.
C# OOP PRACTICE
Ex 3
Create a C# program to manage a photo book using object-oriented Input
programming.
To start, create a class called PhotoBook with a private
attribute numPages of type int. It must also have a public
method GetNumberPages that will return the number of photo book Output
pages. 16
The default constructor will create an album with 16 pages. There will be 24
64
an additional constructor, with which we can specify the number of pages
we want in the album.
There is also a BigPhotoBook class whose constructor will create an
album with 64 pages.
In Program.cs perform the following actions:
• Create a default photo book and show the number of pages
• Create a photo book with 24 pages and show the number of pages
• Create a large photo book and show the number of pages
C# OOP PRACTICE
Ex 4
Create a C# program that prompts the user for three names of people and Input
stores them in an array of Person-type objects. There will be two people Jana
of the Student type and one person of the Teacher type. Sara
To do this, create a Person class that has a Name property of type string, Chaitanya
a constructor that receives the name as a parameter and overrides the
ToString () method.
Then create two more classes that inherit from the Person class, they will Output
Explain
be called Student and Teacher. The Student class has a Study method
Study
that writes to the console that the student is studying. The Teacher class
will have an Explain method that writes to the console that the teacher is Study
explaining. Remember to also create two constructors on the child
classes that call the parent constructor of the Person class.
End the program by reading the people (the teacher and the students)
and execute the Explain and Study methods.
C# OOP PRACTICE
Ex 5
Create a C# program that implements an IVehicle interface with two Input
methods, one for Drive of type void and another for Refuel of type bool 50
that has a parameter of type integer with the amount of petrol to refuel.
Then create a Car class with a builder that receives a parameter with the
car's starting petrol amount and implements the Drive and Refuel Output
methods of the car. Driving
The Drive method will print on the screen that the car is Driving, if petrol is
greater than 0. The Refuel method will increase the petrol of the car and
return true.
To carry out the tests, create an object of type Car with 0 of petrol in
Program.cs and ask the user for an amount of petrol to refuel, finally
execute the Drive method of the car.
C# OOP PRACTICE
Ex 6
Create a C# program that implements an abstract class Animal that has a Input
Name property of type text and three methods SetName (string name), Tommy
GetName and Eat. The Eat method will be an abstract method of type
void.
You will also need to create a Dog class that implements the above Output
Animal class and the Eat method that says the dog is Eating. Tommy
To test the program ask the user for a dog name and create a new Dog Eating
type object in Program.cs, give the Dog object a name, and then execute
the GetName and Eat methods.
C# OOP PRACTICE
Ex 7
Create a class to store details of student like rollno, name, course joined Input
and fee paid so far. Assume courses are C# and RDBMS with course fees 1
being 20000 and 15000 respectively. Akshat Shastri
Provide a constructor to take rollno, name and course. C#
Provide the following methods:
Output
Payment(amount) to pay part/ full fees which will be saved. Hello, Akshat
Print() to print details of the student with fees paid. Shastri. Your
DueAmount property course fee is
TotalFee property Rs__.
Add a static member to store Service Tax, which is set to 12.3%. Also
allow a property through which we can set and get service tax.
Modify TotalFee and DueAmount properties to consider service tax.
C# OOP PRACTICE
Ex 8
Create the classes required to store data regarding different types of Input
Courses in an institute. All courses have course serial number, name,
duration in months, number of students and course fee per student.
Courses may be part-time or full-time where you must store the time per Output
day for that course. Part-time courses will run for 4 hours per day and full-
time courses run for 8 hours in a day.
Some courses are onsite where you must store the company name and
the number of candidates for the course.
For onsite course charge 10% more on the course fee. For part-time
course, offer 10% discount to the course fee.
Provide constructors and the following methods.
Print() to print relevant details of the course.
GetTotalFee() that prints the fee received from running a particular
course.

You might also like