0% found this document useful (0 votes)
31 views28 pages

Session 2

The document discusses object-oriented programming concepts in C# including defining classes, access modifiers, class members like fields, properties, methods, constructors, and object initializers. It provides examples and explanations of these concepts across 26 slides.
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)
31 views28 pages

Session 2

The document discusses object-oriented programming concepts in C# including defining classes, access modifiers, class members like fields, properties, methods, constructors, and object initializers. It provides examples and explanations of these concepts across 26 slides.
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/ 28

DCIT 318

PROGRAMMING II

Session 2 OOP using C#

Lecturer: Mr. Paul Ammah, CSD


Contact Information: [email protected]

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
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 6
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 7
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 8
Fields & Properties
class Person {
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}

Slide 9
Fields & Properties
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 10
}
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 11
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 12
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 13
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 14
C# Conditions and If Statements
• If Condition
if (condition) {
// block of code to be executed if the condition is True
}

if (condition) {
// block of code to be executed if the condition is True
} else {
// block of code to be executed if the condition is False
}

• Ternary Operator
variable = (condition) ? expressionTrue : expressionFalse;

Slide 15
C# Switch Statements
switch(expression) {
case x:
// code block
break;

case y:
// code block
break;

default:
// code block
break;
}

Slide 16
Loops
• while (condition) {
// code block to be executed
}

• do {
// code block to be executed
} while (condition);

• for (statement 1; statement 2; statement 3) {


// code block to be executed
}

Slide 17
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 18
Default Parameter Value
• You can also use a default parameter value, by using the equals
sign (=).
• If we call the method without an argument, it uses the default
value

static void MyMethod(string country = "Norway") {


Console.WriteLine(country);
}

MyMethod();
MyMethod("USA");

Slide 19
Named Arguments
• It is also possible to send arguments with the key: value
syntax.

static void MyMethod(string child1, string child2, string child3) {


Console.WriteLine("The youngest child is: " + child3);
}

static void Main(string[] args) {


MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}

Slide 20
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 21
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 22
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 23
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 24
Private Constructors
class NLog
{
// Private Constructor:
private NLog() { }

public static double e = Math.E;


}

Slide 25
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 26
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 27
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 28

You might also like