$RXOPFPA

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

DCIT 318

PROGRAMMING II

Session 2 – OOP using C#

Lecturer: Mr. Paul Ammah, CSD


Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Defining a class
using System;
namespace Lecture2
{
public class Person
{
}
}

Slide 2
Access Modifiers

Slide 3
Class Members
• Classes and structs have members that represent
their data and behavior.
• A class's members include all the members declared
in the class, along with all members (except
constructors and finalizers) declared in all classes in
its inheritance hierarchy

Slide 4
Class Members contd.
• Fields are variables declared at class scope. A field may be a built-in
numeric type or an instance of another class
• Constants are fields whose value is set at compile time and cannot be
changed.
• Properties are methods on a class that are accessed as if they were fields
on that class
• Methods define the actions that a class can perform.
• Constructors are methods that are called when the object is first created.
• Indexers enable an object to be indexed in a manner similar to arrays.
• Operators: Overloaded operators are considered type members
• Events provide notifications about occurrences, such as button clicks or
the successful completion of a method, to other objects

Slide 5
Fields
• A class or struct may have instance fields, static
fields, or both.
• Generally, you should declare fields as private or
protected accessibility
• Fields typically store the data that must be accessible
to more than one type method and must be stored
for longer than the lifetime of any single method

Slide 6
Fields
public class CalendarEntry
{

// private field (Located near wrapping "Date" property).


private DateTime _date;

// Public property exposes _date field safely.


public DateTime Date
{
get
{
return _date;
}
set
{
// Set some reasonable boundaries for likely birth dates.
if (value.Year > 1900 && value.Year <= DateTime.Today.Year)
{
_date = value;
}
else
{
throw new ArgumentOutOfRangeException("Date");
}
}
}

} Slide 7
Constants
• Constants are immutable values which are known at
compile time and do not change for the life of the
program.
• Constants can be marked as public, private, protected,
internal, protected internal or private protected.
class Calendar1
{
public const int Months = 12;
public const int Weeks = 52, Days = 365;
}
Slide 8
Properties
• A property is a member that provides a flexible mechanism to
read, write, or compute the value of a private field.
• Properties can be used as if they're public data members, but
they're special methods called accessors
• A get property accessor is used to return the property value,
and a set property accessor is used to assign a new value
• 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)

Slide 9
Auto-Implemented Properties
• Auto-implemented properties make property-
declaration more concise when no additional logic is
required in the property accessors

public class Customer {


//Auto-implemented properties for trivial get and set

public double TotalPurchases { get; set; }


public string Name { get; set; } = "Jane";
public int CustomerId { get; set; }

Slide 10
Properties with backing fields
public class TimePeriod
{
private double _seconds;

public double Hours


{
get { return _seconds / 3600; }
set
{
if (value < 0 || value > 24)
throw new ArgumentOutOfRangeException(nameof(value),
"The valid range is between 0 and 24.");

_seconds = value * 3600;


}
}
}

Slide 11
Required Properties
• Beginning with C# 11, you can add the required member to
force client code to initialize any property or field:
public class SaleItem
{
public required string Name
{ get; set; }

public required decimal Price


{ get; set; }
}

Slide 12
Required Properties contd.
• To create a SaleItem, you must set both the Name
and Price properties using object initializers

var item = new SaleItem { Name = "Shoes",


Price = 19.95m };

Slide 13
Methods
• A method is a code block that contains a series of statements.

class SimpleMath
{
public int AddTwoNumbers(int num1, int num2)
{
return num1 + num2;
}

public int SquareANumber(int number)


{
return number * number;
}
}

Slide 14
Method Overloading
• Two or more methods in a class with the same name but different numbers, types,
and order of parameters, it is called method overloading

namespace MethodOverload {

class Program {

// method with one parameter


void display(int a) {
Console.WriteLine("Arguments: " + a);
}

// method with two parameters


void display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b);
}
}
}

Slide 15
Constructors
• Whenever an instance of a class or a struct is created, its constructor is called.
• A class or struct may have multiple constructors that take different arguments.
public class Person
{
private string last;
private string first;

public Person(string lastName, string firstName)


{
last = lastName;
first = firstName;
}

// Remaining implementation of Person class.


}

Slide 16
Constructors contd
class Coords
{
public Coords()
: this(0, 0)
{ }

public Coords(int x, int y)


{
X = x;
Y = y;
}

public int X { get; set; }


public int Y { get; set; }

Slide 17
Private Constructors
• A private constructor is a special instance
constructor.
• It is generally used in classes that contain static
members only.
• If a class has one or more private constructors and no
public constructors, other classes (except nested
classes) cannot create instances of this class

Slide 18
Private Constructors
class NLog
{
// Private Constructor:
private NLog() { }

public static double e = Math.E;


}

Slide 19
Object Initializers
• 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
• The object initializer syntax enables you to specify
arguments for a constructor or omit the arguments
(and parentheses syntax)

Slide 20
Object Initializers
public class Cat
{
public int Age { get; set; }
public string? Name {get; set;}

public Cat()
{
}

public Cat(string name)


{
this.Name = name;
}
}

Cat cat = new Cat { Age = 10, Name = "Fluffy" };


Cat sameCat = new Cat("Fluffy"){ Age = 10 };

Slide 21
Collection initializers
• Collection initializers let you specify one or more
element initializers when you initialize a collection
type that implements IEnumerable

List<Cat> cats = new List<Cat>


{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};

Slide 22

You might also like