0% found this document useful (0 votes)
23 views31 pages

Week2 1

pj

Uploaded by

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

Week2 1

pj

Uploaded by

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

VISUAL PROGRAMMING

Engr. Anees Ahmed Soomro


Assistant Professor
CS QUEST Nawabshah

https://anees-soomro.neocities.org
OOP CONCEPTS

1) Namespaces , Passing arguments by reference or


value
2) Returning more than one value
3) OOP – access modifiers, properties, constructors
4) OOP- inheritance
Type
Predefined types
Size Range BCL Name Signed Literal Suffix

sbyte 8 bits -128 to 127 System.SByte Yes

byte 8 bits 0 to 255 System.Byte No

short 16 bits -32,768 to 32,767 System.Int16 Yes

ushort 16 bits 0 to 65,535 System.UInt16 No

int 32 bits -2,147,483,648 to System.Int32 Yes


2,147,483,647
uint 32 bits 0 to 4,294,967,295 System.UInt32 No U or u

long 64 bits -9.2e18 to 9.2e18 System.Int64 Yes L or l

ulong 64 bits 18.4e18 System.UInt64 No UL or ul

float 32 bits +-1.5e-45 to +-3.4e38 System.Single Yes F or f

double 64 bits +-5.0e-324 to +-1.7e308 System.Double Yes D or d

decimal 128 bits +-1.0e-28 to +-7.9e28 System.Decimal Yes M or m

char 16 bits 65536 characters System.Char

bool 8 bits true or false System.Boolean

All these types are value types


Value types vs Reference types
Value types: Reference types:

A variable contains the data A variable contains a reference to


directly. the data.

Examples: Examples:
all primitive types from last slide strings, arrays, objects
and structs

decimal x = 8; string a = "abc";


decimal y = string b = "abracadabra";
9; a = b; // only a reference is copied
x = y; // 16 // (typically 4-8 bytes)
bytes of data
Declarations
int myInteger;
myInteger = 1;
int yourTnteger =
0;

char x;
x = '\u0020'; //
char y = 'c'; blank

float height1;
height1 = 1.443F;
float height2 =
float.Parse("1.22
2");

string s;
s = "def";
string t =
"abc";

int[]
values;
int count
values= =more.Length; // will be 3
new int[] {
3, 2, 7, 18
};
Conditions
if (more.Length == if (<boolean>)
14) {
{ evenmore[0] += ...
22; }
}
if (more.Length < 10) { evenmore[0] +=
22;
} else {
evenmore[2] = -17;
}

if (more.Length < 10) { evenmore[0] +=


22;
} else if(more.Length > 102) { evenmore[1] = 8;
} else {
System.Console.WriteLine("why?");
}
Loops
do
{
a = int.Parse(System.Console.ReadLine());
}
while (a != 0);

while (a < 10)


{
System.Console.WriteLine("Here is your integer: {0}\n", a);
a++;
}

for (a = 0; a < 10; a++)


{
System.Console.WriteLine("Counting...\n");
}

foreach(int x in values)
{ if(x > currentMax){
currentMax = x;
}
}
Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
+, -, *, / Arithmetic operators
% Rest of integer division (Remainder)
<, <=, ==, !=, >=, > Comparing operators
++x, x++, --i, i-- Pre- and post-incrementing / decrementing

Operator Meaning
|, &, ^ Binary OR, AND, XOR
<< Binary leftshift
>> Binary rightshift
Methods (functions)
public int computeMax(int[] values)
{
int currentMax = values[0];

foreach(int x in values){ if(x > currentMax){


currentMax = x;
}
}
return currentMax;
}
Objects
Everything in C# is in a
class. Nothing exists without
a class.

A class is a template for an


object.
An object has fields (data)
and methods (functions).

Recall HelloWorld:

using System;
class HelloWorld
{
static void
Main()
{
Console.W
riteLine(
"Hello
world!");
}
Objects
class Employee
{
private string FirstName; 2 fields
private string LastName;

public string GetName() 1 method


{
return string.Concat(FirstName, " ",
LastName);
} }
Namespaces

grouping types to an area of functionality (similar to java packages)

hierarchical

see e.g., System, System.IO, System.Console

using System; namespace Namespace02


using SpecialCar = Namespace02.Car; // {
alias class Car
namespace Namespace01 {
{ public string name;
class Car }
{ }
public string name;
public int age;
}

class Program
{
static void Main(string[] args)
{
Namespace02.Car carA = new
Namespace02.Car(); Car carB = new Car();
SpecialCar carC = new SpecialCar();

System.Console.WriteLine("Abraham");
Console.WriteLine("Bebraham"); //
possible due to the "using System";
}
}
Passing arguments by reference or value
Passing by value
public void Swap(int a, int b) public void Swap(string a, string b)
{ {
int temp = a; string temp = a;
a = b; a = b;
b = temp; b = temp;
} }

does not affect the assigned values in the caller.

Passing by reference

public void SwapRef(ref int a, ref int b) public void SwapRef(ref string a, ref strin
{ b)
int temp = a; {
a = b; string temp = a;
b = temp; a = b;
} b = temp;
}
does affect the assigned values in the caller.
Returning more than one value
Calling code:
public int GetMax(int[] values)
{ a = GetMax(myArray);
return values.Max();
}

Returning two values via references


public void GetMinMax(int[] values, ref int max, ref int GetMinMax(myArray, ref a, ref
min) b);
{
max = values.Max();
min =
values.Min();
}

Better: use the out keyword


public void GetMinMax(int[] values, out int max, out int GetMinMax(myArray, out a, out
min) b);
{
max = values.Max();
min =
values.Min();
}
OOP
A class is a template for an object.
Several (different) objects can be instantiated from a class.

class Employee Employee employee1 = new


{ Employee(); Employee employee2;
public string Name;
public int Salary; employee1.Name = "Karl
Karlsson"; employee1.Salary =
public void PrintInfo() 14000; employee1.PrintInfo();
{
Console.WriteLine("Name: " + Name); employee2 = new Employee();
Console.WriteLine("Salary: {0}", Salary); employee2.Name = "Nils
} Nilsson"; employee2.Salary =
public void IncreaseSalary(int amount) 20000;
{ employee2.IncreaseSalary(3000);
Salary += amount; employee2.PrintInfo();
}
public void SetSalary(int salary)
{ Output:
this.Salary = salary;
} Name: Karl
} Karlsson Salary:
14000 Name: Nils
public void Save() Nilsson Salary:
{ 23000
DataStorage.Store(this);
}
OOP – access modifiers
class Example
{
public int a; // access from everywhere
private int b; // access only from inside the class
protected int c; // access from inside the class and subclasses (inherited
internal int d; classes)
int e; // access from everywhere within the same assembly

public void PrintInfo()


{
System.Console.WriteLine("a: " + a);
System.Console.WriteLine("b: " + b);
System.Console.WriteLine("c: " + c);
System.Console.WriteLine("d: " + d);
}
}
OOP – properties
Property: behaves from the outside as a field. But is more complex.

public string FirstName // property name


{
get
{
return _FirstName;
}
set
{
_FirstName = FirstName;
}
}
private string _FirstName; // backing field
OOP – properties
Property: behaves from the outside as a field. But is more complex.

public string FirstName // property name


{
get
{
return _FirstName;
}
set
{
if (value != null)
{
_FirstName = value;
}
else
{
_FirstName = "";
}
}
}
private string _FirstName; // backing field
OOP – properties
Property: behaves from the outside as a field. But is more complex.

Motivation for properties:



public is often too open / dangerous for a field.
● but private/protected is too restrictive

● avoid hassle with getters and setters

Property features:

read-only (without getter setter methods)
● write-only (without getter setter methods) a

● property can not be passed as a reference

● different access modifiers for read and write

access
When to use a property, when a field?

Property: if simple access to data and no complex computation.

Otherwise field with getter and setter.

Basic rule: avoid public/protected. Make it a propery instead.


OOP – properties
// write only
public string Title
{
set
{ // from ouside the class: read
_Title = value;
only
}
// inside: read and write
}
access public string
private string _Title;
Description
{
get
{
// read only
return _Description;
public string Comment
}
{
private set
get
{
{
_Description = value;
return _Comment;
}
}
}
}
private string _Description;
private string _Comment;
OOP – properties
// a propery as virtual field (i.e. without backing field) public
string Name
{
get
{
return FirstName + " " + LastName;
}
set
{
string[] names;
names = value.Split((new char[] { ' ' }));
FirstName = names[0];
LastName = names[1];
}
}
OOP – constuctor
class Employee
{
public string Name;
public int Salary;

// Constructor with two parameters (overloading the


constructor) public Employee(string name, int salary)
{
Name = name;
Salary = salary;
}

// Overriding the default constructor


public Employee()
{
Name = "";
Salary = 0;
}

// note: as soon
as you define ANY
constructor,
// the default
constructor is no
longer available
}
OOP – inheritance
class PdaItem
{
public string Name { get; set; }
public DateTime LastUpdated { get;
set; }
}
class Contact : PdaItem In C# only single inheritance!
{
public string Address { get;
set; } public string Phone
{ get; set; }
}

class Program
{

static void Main(string[] args)


{
PdaItem PdaItem = new PdaItem();
Contact Contact = new Contact();

PdaItem = Contact; // implicit conversion


Contact = (Contact)PdaItem;
// explicit conversion required via
} casting
}
OOP – overriding methods or properties
Use virtual to make a methods or property overridable (otherwise no overriding possible).
Use override when overriding (mandatory).

class PdaItem
{
public virtual string Name { get; set; }
}

class Contact : PdaItem You can not override fields!


{
public override string Name
{
get
{
return FirstName + " " + LastName;
}
set
{
string[] names = value.Split(' ');
FirstName = names[0];
LastName = names[1];
}
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
OOP – avoid inheritance
// sealed corresponds to final in Java

sealed class PdaItem


{
public string Name { get; set; }
public DateTime LastUpdated { get;
set; }
}

// does not compile!


class Contact :
PdaItem
{
public string Address { get;
set; } public string Phone
{ get; set; }
}
OOP – avoid overriding
class A
{
public virtual void Method()
{

}
}

class B : A
{
public override sealed void
Method()
{

}
}

class C : B
{
// does not compile!
public override void Method()
{

}
}
OOP – base class
class A
{
public virtual void Method()
{
Console.WriteLine("Honolulu"
);
}
}

class B : A
{
public override void Method()
{
base.Method();
Console.WriteLine("+
Luluhono");
}
}
OOP – abstract classes
Abstract classes

represent abstract entities.
● can not be instantiated, only derived

● have abstract members which have to be implemented (overridden) by derived classes.

abstract class Vehicle


{
int ID;
public abstract void Drive();
}

class Car : Vehicle


{
public override void Drive()
{
Console.WriteLine("Driving
");
}
}
class Program
{
static void Main(string[]
args)
{
// Vehicle v = new Vehicle(); // you can not instantiate from an abstrac
Vehicle c = new Car(); class!
}
}
OOP – System.Object
Every class inherits from object (System.Object) the following methods:

Name Description

public virtual bool Determines whether the specified object is equal to


Equals(Object) the current object.
public virtual bool Equals(Object, Determines whether the specified object instances
Object) are considered equal.
public virtual int Serves as the default hash function. Gets the
GetHashCode()
public Type GetType() Type of the current instance.
Determines whether the specified object instances are the
public static bool
same instance.
ReferenceEquals()
Returns a string that represents the current object.
public virtual string
Allows an object to try to free resources and perform other
ToString()
protected virtual void cleanup operations before it is reclaimed by garbage
Finalize() collection.

protected Object Creates a shallow copy of the current


MemberwiseClone() Object.
OOP – check type with is
class Car
{
int NumWheels = 4;
}

static void Main(string[] args)


{
object data = "Timbuktu";
object data2 = new Car();

Console.WriteLine(data is string); // True


} Console.WriteLine(data2 is string); // False
OOP – Interfaces
Interfaces are contracts.
A class implementing an interface "promises" to implement certain methods.
Declaration as a class, but contains only declarations no definitions.
And only methods or properties. No fields.

Declaration: Implementation:
class Contact : PdaItem, IListable You can implement
interface IListable {
{ multiple
public string FirstName;
string[] Values interfaces.
public string LastName;
{ public string Address;
get;
}
}
public string[] Values
{
get
{
return new string[] { FirstName, LastName, Address }
}
} }
Usage:

Contact Contact = new Contact() { FirstName = "Hans", LastName = "Hansson", Address =

"Kungsgatan"}; foreach(string s in Contact.Values)


{
Console.WriteLine(s);
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy