0% found this document useful (0 votes)
9 views

Visual Week 2

Uploaded by

hmdnisa1907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Visual Week 2

Uploaded by

hmdnisa1907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 178

VISUAL PROGRAMMING

• Assoc. Prof. Dr. Mehmet Akif Cifci

• Vienna University of Technology, Austria


• Klaipeda University, Lithuania
• Bandırma Onyedi Eylül University, Turkey
• Istanbul Topkapı University, Turkey
• Deakin University, Australia
• IEEE Best Researcher Award
• MPDI Top Paper Award
C# Programming Object
Oriented Programming
(OOP)
• This module assumes that you understand
the fundamentals of
• Programming
• Variables, statements, functions,
loops, etc.
Prerequisites • Object-oriented programming
• Classes, inheritance,
polymorphism,
members, etc.
• C++ or Java
C# design goals

Fundamentals of the
Types, program structure, statements, operators
C# language

Learning
Objectives Be able to begin
Using the .NET Framework SDK
writing and
debugging C# Using Visual Studio.NET
programs

Be able to write
individual C#
methods
Design Goals
Hello World Types
of C#

Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
Hello World

using System; class Hello { static void Main( ) {

Console.WriteLine("Hello
world");
• Console.ReadLine(); // Hit } }
enter to finish
Design Goals
Hello World Types
of C#

Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
Design Goals of C#
The Big Ideas

Robust and Preserving


Component- Everything is
durable your
orientation an object
software investment
Design Goals of C#
Component-Orientation

C# is the first “Component-Oriented” language in the C/C++


family

What is a component?
In general, component writer and
Coarser-grained than objects
An independent module of reuse user don’t know each other, don’t
(objects are language-level Includes multiple classes Often language-independent
and deployment work for the same company, and
constructs)
don’t use the same language
Component concepts are first class
Design Goals
• Properties, methods, events
of C# • Design-time and run-time attributes
Component- • Integrated documentation using XML
Orientation
Enables “one-stop programming”

• No header files, IDL, etc.


• Can be embedded in ASP pages
• Traditional views
• C++, Java™: Primitive types are “magic” and do
not interoperate with objects
Design Goals • Smalltalk, Lisp: Primitive types are objects, but
of C# at some performance cost
• C# unifies with no performance cost
Everything is • Deep simplicity throughout system
an Object • Improved extensibility and reusability
• New primitive types: Decimal, SQL…
• Collections, etc., work for all types
Design Goals of C#
Robust and Durable Software
Garbage collection No memory leaks and stray pointers

Exceptions

Type-safety No uninitialized variables, no unsafe casts

Versioning

Avoid common
E.g. if (x = y) ...
errors
One-stop
Fewer moving parts
programming
Design Goals of C#
Preserving Your Investment

C++ Heritage Interoperability Increased productivity


Namespaces, pointers (in unsafe What software is increasingly about Short learning curve
code), C# talks to XML, SOAP, COM, DLLs, Millions of lines of C# code in .NET
unsigned types, etc. and any
Some changes, but no unnecessary .NET Framework language
sacrifices
Design Goals
Hello World Types
of C#

Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
A C# program is a collection of types

• Classes, structs, enums, interfaces, delegates

C# provides a set of predefined types

Types • E.g. int, byte, char, string, object, …


Overview You can create your own types

All data and code is defined within


a type
• No global variables, no global functions
• Types contain:
• Data members
• Fields, constants, arrays
• Events
Types • Function members
• Methods, operators, constructors,
Overview destructors
• Properties, indexers
• Other types
• Classes, structs, enums,
interfaces, delegates
Types can be …and then used: call methods,
instantiated… get and set properties, etc.

Can convert
from one type Implicitly and explicitly
to another

Types Types are Namespaces, files, assemblies


organized
Overview
There are two
categories of
types:
value and
reference

Types are
arranged in a
hierarchy
Types
Unified Type System

Value types Reference types


• Directly contain data • Contain references to
• Cannot be null objects
• May be null

int i = 123; i 123


string s = "Hello world";
s "Hello world"
Types
Unified Type System
Value types

• Primitives int i; float x;


• Enums enum State { Off, On }
• Structs struct Point {int x,y;}

Reference types

• Root object
• String string
• Classes class Foo: Bar, IFoo {...}
• Interfaces interface IFoo: IBar {...}
• Arrays string[] a = new string[10];
• Delegates delegate void Empty();
Value Reference
(Struct) (Class)
Variable Memory
Actual value
holds location
Stack,
Allocated on Heap
member
Types Nullability
Always has
value
May be null

Unified Type Default value 0 null

System Aliasing (in a


scope)
No Yes

Assignment Copy
Copy data
means reference
Types • Benefits of value types
• No heap allocation, less GC pressure
Unified Type • More efficient use of memory
System • Less reference indirection
• Unified type system
• No primitive/object dichotomy
Implicit conversions

• Occur automatically
• Guaranteed to succeed
• No information (precision) loss

Types Explicit conversions

Conversions • Require a cast


• May not succeed
• Information (precision) might be lost

Both implicit and explicit conversions can be user-defined


• int x = 123456;
• long y = x;
// implicit
Types • short z = (short)x; // explicit

Conversions • double d = 1.2345678901234;


• float f = (float)d; // explicit
• long l = (long)d;
// explicit
• Unboxing
• Inverse operation of boxing
Types • Copies the value out of the box
Unified Type • Copies from reference type to
value type
System • Requires an explicit conversion
• May not succeed (like all explicit
conversions)
• Essentially a “down cast”
Types
Predefined Types

Value Reference
Integral types object
Floating point types string
decimal
bool
char
Predefined Types
Value Types
• All are predefined structs

Signed sbyte, short, int, long

Unsigned byte, ushort, uint, ulong

Character char

Floating point float, double, decimal

Logical bool
Predefined Types
Integral Types

C# Type System Type Size (bytes) Signed?


sbyte System.Sbyte 1 Yes
short System.Int16 2 Yes
int System.Int32 4 Yes
long System.Int64 8 Yes
byte System.Byte 1 No
ushort System.UInt16 2 No
uint System.UInt32 4 No
ulong System.UInt64 8 No
Predefined Types
Floating Point Types
• Follows IEEE 754 specification
• Supports ± 0, ± Infinity, NaN

C# Type System Type Size (bytes)


float System.Single 4
double System.Double 8
Predefined Types
decimal
• 128 bits
• Essentially a 96 bit value scaled by a
power of 10
• Decimal values represented precisely
• Doesn’t support signed zeros, infinities
or NaN

C# Type System Type Size (bytes)


decimal System.Decimal 16
Predefined Types
decimal

All integer types can be implicitly converted Conversions between decimal and floating s * m * 10e
to a decimal type types require explicit conversion due to
possible loss of precision
s = 1 or –1
0  m  296
-28  e  0
Predefined Types
Integral Literals
• Integer literals can be expressed as decimal
or hexadecimal
• U or u: uint or ulong
• L or l: long or ulong
• UL or ul: ulong

123 // Decimal
0x7B // Hexadecimal
123U // Unsigned
123ul // Unsigned long
123L // Long
Predefined Types
Real Literals
• F or f: float
• D or d: double
• M or m: decimal

123f // Float
123D // Double
123.456m // Decimal
1.23e2f // Float
12.3E1M // Decimal
Predefined Types
bool
• Represents logical values
• Literal values are true and false
• Cannot use 1 and 0 as boolean values
• No standard conversion between other types
and bool

C# Type System Type Size (bytes)


bool System.Boolean 1 (2 for arrays)
Predefined Types
char
• Represents a Unicode character
• Literals
• ‘A’ // Simple character
• ‘\u0041’ // Unicode
• ‘\x0041’ // Unsigned short hexadecimal
• ‘\n’ // Escape sequence character

C# Type System Type Size (bytes)


Char System.Char 2
Predefined Types
char
• Escape sequence characters (partial list)

Char Meaning Value


\’ Single quote 0x0027
\” Double quote 0x0022
\\ Backslash 0x005C
\0 Null 0x0000
\n New line 0x000A
\r Carriage return 0x000D
\t Tab 0x0009
Predefined Types
Reference Types

Root type object

Character string string


Predefined Types
object
• Root of object hierarchy
• Storage (book keeping) overhead
• 0 bytes for value types
• 8 bytes for reference types
• An actual reference (not the object)
uses 4 bytes

C# Type System Type Size (bytes)


object System.Object 0/8 overhead
public string public bool
ToString() Equals(object)

Predefined
Types protected void

object Public
public void Object()
Finalize()

Methods
protected object public int
MemberwiseClone() GetHashCode()

public System.Type
GetType()
Predefined Types
string
• An immutable sequence of Unicode characters
• Reference type
• Special syntax for literals
• string s = “I am a string”;

C# Type System Type Size (bytes)


String System.String 20 minimum
Predefined Types
string
• Normally have to use escape characters
string s1= “\\\\server\\fileshare\\filename.cs”;

• Verbatim string literals


• Most escape sequences ignored
• Except for “”
• Verbatim literals can be multi-line

string s2 = @“\\server\fileshare\filename.cs”;
Types
User-defined Types
• User-defined types

Enumerations enum

Arrays int[], string[]

Interface interface

Reference type class

Value type struct

Function pointer delegate


Types
Enums

An enum defines a type name Choices must be known at Strongly typed Can specify underlying type
for a related group of symbolic compile-time
constants
No implicit conversions to/from int byte, sbyte, short, ushort, int, uint, long,
Can be explicitly converted ulong
Operators: +, -, ++, --, &, |, ^, ~, …
Types
Enums

enum Color: byte {


Red = 1,
Green = 2,
Blue = 4,
Black = 0,
White = Red | Green | Blue
}

Color c = Color.Black;
Console.WriteLine(c); // 0
Console.WriteLine(c.Format()); // Black
• All enums derive from System.Enum
• Provides methods to
Types • determine underlying type
• test if a value is supported
Enums • initialize from string constant
• retrieve all values in enum
• …
Types
Arrays
• Arrays allow a group of elements of a specific
type to be stored in a contiguous block of
memory
• Arrays are reference types
• Derived from System.Array
• Zero-based
• Can be multidimensional
• Arrays know their length(s) and rank
• Bounds checking
Types
Arrays

int[] primes; Declare

int[] primes = new int[9];

int[] prime = new int[] {1,2,3,5,7,11,13,17,19};


int[] prime = {1,2,3,5,7,11,13,17,19};

prime2[i] = prime[i];

foreach (int i in prime) Console.WriteLine(i);


• Multidimensional arrays
• Rectangular
• int[,] matR = new
int[2,3];
• Can initialize declaratively
Types • int[,] matR =
new int[2,3] {
Arrays {1,2,3}, {4,5,6} };
• Jagged
• An array of arrays
• int[][] matJ = new
int[2][];
• Must initialize procedurally
An interface defines a contract

• Includes methods, properties, indexers, events


• Any class or struct implementing an interface
must support all parts of the contract

Types Interfaces provide polymorphism


Interfaces • Many classes and structs may implement
a particular interface

Contain no implementation

• Must be implemented by a class or struct


User-defined reference type

• Similar to C++, Java classes


Types
Single class inheritance
Classes
Multiple interface inheritance
Members

• Constants, fields, methods, operators,


constructors, destructors
• Properties, indexers, events
• Static and instance members
Types
Member access
Classes
• public, protected, private, internal,
protected internal
• Default is private

Instantiated with new operator


Similar to classes, but

• User-defined value type


• Always inherits from object

Ideal for lightweight objects

• int, float, double, etc., are all structs


• User-defined “primitive” types
• Complex, point, rectangle, color, rational
Types Multiple interface inheritance
Structs
Same members as class

Member access

• public, internal, private

Instantiated with new operator


Types
Classes and Structs
struct SPoint { int x, y; ... }
class CPoint { int x, y; ... }

SPoint sp = new SPoint(10, 20);


CPoint cp = new CPoint(10, 20);

10
sp
20

cp CPoint

10
20
Types
Delegates

A delegate is a reference type that When instantiated, a delegate holds Foundation for framework events
defines a method signature one or more methods
Essentially an object-oriented function pointer
Agenda
Hello World
Design Goals of C#
Types
Program Structure
Statements
Operators
Using Visual Studio.NET
Using the .NET Framework SDK
Organizing Types

Namespaces
Program
Structure References
Overview
Main Method

Syntax
Program • Physical organization Assembly
Structure • Types are defined in
files Module
Organizing • Files are compiled File
into
Types modules Type
• Modules are
grouped
into assemblies
Types are defined in files

• A file can contain multiple types


Program • Each type is defined in a single file
Structure
Files are compiled into modules
Organizing
• Module is a DLL or EXE
Types • A module can contain multiple files

Modules are grouped into assemblies

• Assembly can contain multiple modules


• Assemblies and modules are often 1:1
• Types are defined in ONE place
• “One-stop programming”
• No header and source files to
synchronize
• Code is written “in-line”
Program Structure • Declaration and definition are one and
the same
Organizing Types • A type must be fully defined in one file
• Can’t put individual methods in
different files
• No declaration order dependence
• No forward references required
Program Structure
Namespaces
Namespaces provide a way to
uniquely identify a type

Provides logical organization of types

Namespaces can span assemblies

Can nest namespaces

There is no relationship between


namespaces and file structure (unlike Java)

The fully qualified name of a type includes


all namespaces
Program Structure
Namespaces
namespace
class C2 {
N1 { namespace
N2 { //
//
// N1.N2
N1.N2.C2
N1

class C1 {
} }
//
N1.C1

class C2 {

//
} } }
N1.C1.C2
• The using statement lets you • using N1;
Program use types without typing the
Structure fully qualified name
• C1 a; //
• Can always use a fully The N1. is implicit
Namespaces qualified name • N1.C1 b; //
Fully qualified name

• C2 c; //
Error! C2 is undefined
• N1.N2.C2 d; //
One of the C2 classes
• C1.C2 e; //
The other one
• The using statement also lets • using C1 = N1.N2.C1;
Program you create aliases • using N2 = N1.N2;
Structure
• C1 a;
Namespaces Refers to N1.N2.C1
//

• N2.C1 b; //
Refers to N1.N2.C1
Best practice: Put all of your
types in a unique namespace

Program
Have a namespace for your
Structure company, project, product,
etc.
Namespaces

Look at how the .NET


Framework classes are
organized
• In Visual Studio you specify • csc HelloWorld.cs
Program references /reference:System.WinForms
for a project .dll
Structure • Each reference identifies a
References specific assembly
• Passed as reference (/r or
/reference)
to the C# compiler
Namespaces provide language-level naming
shortcuts

Program Don’t have to type a long fully


Structure qualified name over and over
Namespaces
vs. References

References specify which assembly to use


• Execution begins at the static Main()
method
• Can have only one method with one of
the following signatures in an assembly
Program Structure • static void Main()
Main Method • static int Main()
• static void Main(string[]
args)
• static int Main(string[]
args)
• Identifiers
• Names for types, methods, fields, etc.
• Must be whole word – no white space
Program Structure • Unicode characters
Syntax • Begins with letter or underscore
• Case sensitive
• Must not clash with keyword
• Unless prefixed with @
Design Goals
Hello World Types
of C#

Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
• High C++ fidelity • void Foo() {
Statements • if, while, do require bool • i == 1; // error
Overview condition • }
• goto can’t jump into blocks
• switch statement
• No fall-through
• foreach statement
• checked and unchecked
statements
• Expression
statements
must do work
Statement lists

Block statements
 Loop Statements
Labeled statements
◼ while
Declarations ◼ do
◼ for
Statements • Constants
• Variables
◼ foreach
 Jump Statements
Overview Expression statements
◼ break

• checked, uncheckedcontinue
• lock ◼ goto
• using ◼ return
◼ throw
Conditionals
 Exception handling
• if ◼ try
• switch ◼ throw
Statements are terminated with a
semicolon (;)
Statements
Syntax Just like C, C++ and Java

Block statements { ... } don’t need


a semicolon
• Comments
• // Comment a single line,
C++ style
Statements • /* Comment multiple
Syntax C style
lines,

*/
• Statement list: one or more • static void Main() {
Statements statements in sequence • F();
Statement • Block statement: a
statement list delimited by
• G();
• { // Start block
Lists & Block braces { ... }
• H();
Statements •

; // Empty statement
I();
• } // End block
• }
Statements
Variables and Constants

Console.WriteLine(pi
static void Main() { const float pi = 3.14f; const int r = 123; int a;
* r * r);

Console.WriteLine(a
int b = 2, c = 3; a = 1; }
+ b + c);
Statements
Variables and • The scope of a variable or constant runs
from the point of declaration to the end of
Constants the enclosing block
• Within the scope of a
variable or constant it
is an error to declare
another variable or
constant with the same
name

• {
• int x;
• {
Statements • int x; // Error: can’t
hide variable x
Variables and Constants • }
• }
• Variables must be assigned a value
before they can be used
• Explicitly or automatically
• Called definite assignment
• Automatic assignment occurs for
static fields, class instance fields and
array elements

• void Foo() {
• string s;
Statements • Console.WriteLine(s); //
Error
Variables • }
• goto can be used to
transfer control within
or out of a block, but
not into a nested block

• static void Find(int value, int[,] values,


• out int row, out int col) {
• int i, j;

Statements •

for (i = 0; i < values.GetLength(0); i++)
for (j = 0; j < values.GetLength(1); j++)

Labeled Statements & •



if (values[i, j] == value) goto found;
throw new InvalidOperationException(“Not
found");

goto •

found:
row = i; col = j;
• }
• Statements must do
work
• Assignment,
method call, ++, --,
new

• static void Main() {


• int a, b = 2, c = 3;
• a = b + c;
• a++;
Statements • MyClass.Foo(a,b,c);
• Console.WriteLine(a + b + c);
Expression Statements • a == 2;
// ERROR!
• }
• Requires bool
expression

• int Test(int a, int b) {


• if (a > b)
• return 1;
Statements • else if (a < b)
• return -1;
if Statement • else
• return 0;
• }
Can branch on any predefined type
(including string) or enum

User-defined types can provide implicit conversion

Statements to these types

switch
Statement
Must explicitly state how to end case

With break, goto case, Not needed if no code


Eliminates fall-
goto label, return, supplied after the
through bugs
throw or continue label
• int Test(string label) {
• int result;
• switch(label) {
• case null:
• goto case “runner-up”;

Statements •

case “fastest”:
case “winner”:
switch •

result = 1; break;
case “runner-up”:
Statement •

result = 2; break;
default:
• result = 0;
• }
• return result;
• }
Statements
while Statement
• Requires bool expression

int i = 0;
while (i < 5) {
...
i++;
} int i = 0;
do {
...
i++;
}
while (i < 5);
while (true) {
...
}
Statements
for Statement

for (int i=0; i < 5; i++) {


...
}
for (;;) {
...
}
• Iteration of arrays • public static void
Statements Main(string[] args) {
foreach • foreach (string s in args)
• Console.WriteLine(s);
Statement • }
• Iteration of user-defined • foreach (Customer c in
Statements collections customers.OrderBy("name"))
{
foreach • Created by implementing
IEnumerable • if (c.Orders.Count != 0) {
Statement • ...
• }
• }
Statements break
• Exit inner-most loop

Jump
• End iteration of inner-most loop
Statements continue

• Transfer execution to label


goto <label> statement

return
• Exit a method
[<expression>]

• See exception handling


throw
Statements
Exception Handling

Exceptions are the C# mechanism for Superior to returning status values


handling unexpected error conditions
Can’t be ignored
Don’t have to handled at the point they occur
Can be used even where values are not returned
(e.g. accessing a property)
Standard exceptions are provided
Statements
Exception Handling
try...catch...finally statement

try block contains code that


could throw an exception

catch block handles exceptions Can have multiple catch blocks to handle different kinds of exceptions

finally block contains code that Cannot use jump statements (e.g. goto)
will always be executed to exit a finally block
Statements
Exception Handling
throw statement raises an
exception

• Contains information about the exception


An exception is represented as • Properties
an instance of System.Exception • Message
• StackTrace
or derived class • InnerException

You can rethrow an exception,


or catch
one exception and throw
another
• try {
• Console.WriteLine("try");
• throw new Exception(“message”);
• }

Statements •

catch (ArgumentNullException e) {
Console.WriteLine(“caught null argument");
Exception •

}
catch {
Handling •
• }
Console.WriteLine("catch");

• finally {
• Console.WriteLine("finally");
• }
• Multi-threaded applications have to protect
against concurrent access to data
• Must prevent data corruption
• The lock statement uses an instance to
Statements provide mutual exclusion
Synchronization • Only one lock statement can have access to
the same instance
• Actually uses the .NET Framework
System.Threading.Monitor class to
provide mutual exclusion
Statements
Synchronization
public class CheckingAccount {
decimal balance;
public void Deposit(decimal amount) {
lock (this) {
balance += amount;
}
}
public void Withdraw(decimal amount) {
lock (this) {
balance -= amount;
}
}
}
Statements C# uses automatic memory management (garbage collection)

using • Eliminates most memory management problems

Statement However, it results in non-deterministic finalization

• No guarantee as to when and if object destructors


are called
• Objects that need to be cleaned up after
use should implement the
System.IDisposable interface
Statements • One method: Dispose()
• The using statement allows you to create
using Statement an instance, use it, and then ensure that
Dispose is called when done
• Dispose is guaranteed to be called,
as if it were in a finally block
Statements
using Statement
public class MyResource : IDisposable { USING
public void MyResource() { (MYRESOURCE R =
R.DOSOMETHING();
// Acquire valuble resource NEW
MYRESOURCE()) {
}
public void Dispose() {
// Release valuble resource
}
public void DoSomething() { }
... //
R.DISPOSE() IS
}
CALLED
}
Statements
checked and unchecked Statements
The checked and unchecked statements allow you to
control overflow checking for integral-type arithmetic
operations and conversions

checked forces checking

unchecked forces no checking

Can use both as block statements or


as an expression

Default is unchecked

Use the /checked compiler option to make checked


the default
• Console applications • string v1 = “some value”;
Statements • System.Console.WriteLin • MyObject v2 = new
Basic e();
• System.Console.ReadLin
MyObject();
• Console.WriteLine(“First is
Input/Outpu e(); {0}, second is {1}”,
• Windows applications •
t Statements • System.WinForms.Mess v1, v2);
ageBox.Show();
Design Goals
Hello World Types
of C#

Program
Statements Operators
Structure
Agenda
Using the .NET
Using Visual
Framework
Studio.NET
SDK
Operators
Overview

C# provides a fixed set of operators, whose meaning is defined for the predefined types

Some operators can be overloaded (e.g. +)

The following table summarizes the C# operators by category

Categories are in order of decreasing precedence Operators in each category have the same precedence
Operators
Precedence

Category Operators
Grouping: (x)
Member access: x.y
Method call: f(x)
Indexing: a[x]
Post-increment: x++
Primary
Post-decrement: x—
Constructor call: new
Type retrieval: typeof
Arithmetic check on: checked
Arithmetic check off: unchecked
Operators
Precedence

Category Operators
Positive value of: +
Negative value of: -
Not: !
Unary Bitwise complement: ~
Pre-increment: ++x
Post-decrement: --x
Type cast: (T)x
Multiply: *
Multiplicative Divide: /
Division remainder: %
Operators
Precedence

Category Operators
Add: +
Additive
Subtract: -
Shift bits left: <<
Shift
Shift bits right: >>
Less than: <
Greater than: >
Less than or equal to: <=
Relational
Greater than or equal to: >=
Type equality/compatibility: is
Type conversion: as
Operators
Precedence

Category Operators
Equals: ==
Equality
Not equals: !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Operators
Precedence

Category Operators
Ternary
?:
conditional
=, *=, /=, %=, +=, -=, <<=, >>=,
Assignment
&=, ^=, |=
Operators
Associativity

• Assignment and ternary conditional


operators are right-associative
• Operations performed right to left
• x = y = z evaluates as x = (y
= z)
• All other binary operators are left-
associative
• Operations performed left to right
• x + y + z evaluates as (x + y)
+ z
• Use parentheses to control order
How C# Works
How C#
Works
IDE = Integrated Development Environment

Makes you more productive


What is the
IDE? Includes text editör, compiler, debugger,
context-sensitive help, Works with different
SDKs

Visual Studio is the most widely used IDE


Anatomy of
C#
Application
C# Variables

1 2 3 4 5 6

Variables are int - stores integers double - stores floating char - stores single string - stores text, bool - stores values
containers for storing (whole numbers), point numbers, with characters, such as 'a' such as "Hello World". with two states: true
data values. In C#, without decimals, such decimals, such as or 'B'. Char values are String values are or false
there are as 123 or -123 19.99 or -19.99 surrounded by single surrounded by double
different types of quotes quotes
variables (defined with
different keywords),
for example:
C# Operators
Operators are used to perform operations on variables and
values.
C# Types

A C# program is C# provides a set All data and code


You can create
a collection of of predefined is defined within
your own types
types types a type

Classes, structs, No global


İnt, byte, char,
enums, interfaces, variables, no
string, object,..
delegates global functions
• Types contain:
• Data members
• Fields, constans, arrays
• Events
• Function members
C# Types • Methods, operators, constructors,
destructors
• Properties, indexers
• Other types
• Classes, structs, enums, interfaces, delegates
C# Types

Types can be Can convert from one Types are organized There are two categories Types are arranged in a
instantiated: type to another of types: hierarchy
Call methods Implicitly and explicitly Namespaces, files, assemblies Value and referance
Get and set properties etc.
C# Types

Reference
Value types
types

Contain
Directly Cannot be
references to May be null
contain data null
objects
C# Data
Types
Default Values
Uses methods of the
Console class in the
System namespace
Console.ReadLine()
Input /
Output In C# The most widely
used methods are –

Console.WriteLine()
Fundamental
Types Of C#
C# divides data types into two fundamental categories

Value Types

• int, char , and structures

Reference Types

• classes, interfaces, arrays and strings


Value type

• Just hold a value in memory


• Are stored in a stack

Continued Reference type

• Contains the address of the object


in the heap
• = null means that no object has
been referenced
Boxing is conversion of a
value type into a
reference type
Boxing &
Unboxing
Unboxing is the
conversion of a reference
type into a value type
Basic Definitions

• Variable: A name that refers to a


value.
• Assignment statement: Associates
a value with a variable.
Types of iteration constructs
Iteration •

While Loop
Do Loop
Constructs • For Loop
• foreach Loop
If Statement
• The if statement is a common branching structure.
• Evaluate a boolean expression.
• If true, execute some statements.
• If false, execute other statements.
• A common repetition structure.
• Evaluate a boolean expression.
While Loop • If true, execute some statements.
• Repeat.
For Loop
• Another common repetition structure.
• Execute initialization statement.
• Evaluate a boolean expression.
• If true, execute some statements.
• And then inrement statement.
• Repeat.
OOPs is abbreveriated as Object Oriented
Programming system in which programs are
What is the considered as a collection of objects. Each
OOPs? object is nothing but an instance of a class.
Basic Concepts of OOPs

Object Class Inheritance

Polymorphism Encapsulation Abstraction


What is a Class?
• A class is simply a representation of a type
of object. It is the blueprint/plan/template
that describes the details of an object.
What is an An object is an instance of a class. It has its own state,
behavior, and identity.
Object?
What is
Encapsulation?

• Encapsulation is an attribute of an object,


and it contains all data which is hidden.
That hidden data can be restricted to the
members of that class.
• Levels are Public, Protected, Private,
Internal, and Protected Internal.
What is
Polymorphism?
What is Inheritance?
• Inheritance is possible to inherit attributes and
the methods from one class to another class.
There are two types of classes
• Super Class - the class being inherited from
• Sub Class - the class that inherits from another
class
• Types of Inheritance
• Single
• Multiple
• Multi- Level
• Hierarchical
What is an
Abstraction?
• Abstraction is a useful feature of OOPS,
and it shows only the necessary details
to the client of an object. Meaning, it
shows only required details for an
object, not the inner constructors, of an
object. Example - When you want to
switch on the television, it is not
necessary to know the inner
circuitry/mechanism needed to switch
on the TV. Whatever is required to
switch on TV will be shown by using an
abstract class.
C# Programming
Events and Delegates
One of the most interesting concepts in C# is
Event-Driven approach.

Delegation model is a process in which a task is


handed over to some other process so as to
What is a accomplish it.

Delegates? Delegates are the special objects in C# which are


pointers to methods.

Implemented as classes derived from the base


class System.Delegate.
• Basically a function pointer, but are type safe.
• Type safe = A delegate which is pointing to a
return type of int cannot point to a return type
of string.
• Aplaceholder for a/some method(s).
What is a • It is a referance to a function/method. The
Delegates? function is attached to the delegate and will
then can be called via the delegate object.
• Similar to a function pointer, where functions
can be assigned like a variable and called in the
run time based on dynamic conditions.
• Allow methods to be passed as parameters.
Important Points About Delegates

Delegates are mainly used in


Provides a good way to Delegates are the library class in These are the type-safe pointer
implementing the call-back
encapsulate the methods. System namespace. of any method.
methods and events.

Anonymous Methods(C# 2.0)


Delegates can be chained and Lambda expressions(C# 3.0)
Delegates can also be used in
together as two or more It doesn’t care about the class are compiled to delegate types
“anonymous methods”
methods can be called on a of the object that it references. in certain contexts. Sometimes,
invocation.
single event. these features together are
known as anonymous functions.
Historically, the Windows API frequently used C-style function
pointers to create callback functions. Using a callback,
programmers could configure one function to report back to
another function in the application. So the objective of using a

Why Do We
callback is to handle button-clicking, menu-selection, and
mouse-moving activities. But the problem with this traditional
approach is that the callback functions were not type-safe. In the
Need .NET framework, callbacks are still possible using delegates with
a more efficient approach. However, delegates maintain three
Delegates? important pieces of information, as in the following:
• The parameters of the method.
• The address of the method it calls.
• The return type of the method.
A delegate is a solution for situations where you want to pass

Why Do We
methods around to other methods. You are so accustomed to
passing data to methods as parameters that the idea of passing
methods as an argument instead of data might sound a little
Need strange. However, there are cases where you have a method that
does something, for instance, invoking another method. You do
Delegates? not know at compile time what this second method is. That
information is available only at runtime; hence Delegates are the
device to overcome such complications.
Lambda Expressions

• New feature in C# 3.0


• Simplified way to write anonymous
functions
• Including references to the closure
• Lambda expressions makes it simpler to
instantiate delegates
• Example: i => i % 2 == 0
• Left hand side: parameter
• Right hand side: and
expression
• LINQ is a technology that is available as part
of the C# language and makes it easier to
work with data. LINQ allows you to integrate
SQL-like queries into your C# code. This
What is allows you to create queries on databases,
collections, XML documents and other data
LINQ? sources.

• LINQ offers two main approaches: query


expressions and method-based queries.
Query Expressions: Query expressions allow you to express queries using a SQL-
like syntax. This method can help you write clearer and more readable code
when querying data.

Method-Based Queries: Method-based queries use LINQ extension methods to


process LINQ queries. This approach is more suited to a functional programming
style, and LINQ methods allow you to chain operations on collections.
Delegates are extensively used in LINQ to
enable querying and manipulating collections
of objects. The “Where” method in LINQ, for
instance, takes a delegate representing a
predicate that defines the filtering criteria.
This delegate is used to determine whether an
element should be included in the result set.
By providing different predicates, we can
perform various filtering operations on
collections.
Events are notifications

What is a Play a central role in the .NET


Events? framework

Provide a way to trigger notifications


from end usersor from objects
Button Click Event

Events signal the occurrence of an action/notification

Objects that raise events don’t need to explicitly knowthe


object that will handle the event

Events pass EventArgs(event data)


Events Overview
Events have the following properties:

The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.

An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

Events that have no subscribers are never raised.

Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.

When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events
asynchronously, see Calling Synchronous Methods Asynchronously.

In the .NET class library, events are based on the EventHandler delegate and the EventArgs base class.
Basic Event
Declaration

• Here, MyEventHandler is a delegate type


that the event MyEvent is based on.
The RaiseEvent method is used to trigger
the event.
What is an In C# event handling, an “event handler” is a
Event delegate that gets called when a given event is
fired. Like a listener who is waiting for their
Handler in favorite song to play, the event handler is
waiting for the right event to take action.
C#
Step-by-Step Guide to Implementing Events in
C#

1 2 3 4 5
Define a delegate that Declare an event using Implement a method, Create a method in the Subscribe the event
matches the signature the delegate you within the provider subscriber class that handling method to
of the event handler defined. class, that raises the will handle the event the event.
method you want to event. (conforms to the
use. delegate).
C# Programming
Collections
C# collections perform all the data structure work.
Just like an array, a collection can also be used to
store objects with an advantage over an array.

In a collection, the stored object can grow or shrink


dynamically, however, in an array, there is a size
limit.
What is a
Collection? A collection is a set of similarly typed objects that
are grouped together.

The principal benefit of collections is that they


standardize the way groups of objects are handled
by your programs.
Collections are data structures that
holds data in different ways for flexible
operations. C# Collection classes are
defined as part of the System.
Collections or
System.Collentions.Generic namespace.
What is a
Collection? Most collection classes imlement the
same interfaces, and these interfaces
may be inherited to create new
collection classes that fit more
specialized data storage needs.
Generic Collections
Types of
Non-Generic Collections
Collections
Specialized Collections
The System.Collections.Generic namespace
contains interfaces and classes that define
Generic generic collections, which allow users to
Collections create strongly typed collections that provide
better type safety and performance than non-
generic strongly typed collections.
The classes of the
System.Collections.Generic
namespace are listed below:
• List<T>
Generic • Stack<T>
Collections • Queue<T>
• Dictionary<Tkey,Tvalue>
• SortedList<Tkey,Tvalue>
List<T>

Generic List<T> contains elements of specified type. It grows


automatically as you add elements in it.

The List<T> is a collection of strongly typed objects that can be


accessed by index and having methods for sorting, searching and
modifyinf list.
Dictionary<Tkey,Tvalue>
• The Dictionary<Tkey,Tvalue> is a generic
collection that stores key-value pairs in no
particular order and comes under
System.Collections.Generic namespace.
• Implements Idictionary<Tkey, Tvalue> interface.
• Keys must be unique and cannot be null. Values
can be null or duplicate.
• Values can be accessed by passing associated key
in the indexer e.g. myDictionary[key].
• Elements are stored as KeyValuePair<Tkey,
Tvalue> objects.
• SortedList stores key and value pairs. It
automatically adds the elements in
ascending order of a key by default.
• A key must be unique and cannot be null. A
value can be null or duplicate.
SortedList<Tkey,Tvalue>
• It is faster in the retrieval of data once
sorted, whereas
SortedDictionary<Tkey,Tvalue> is faster in
insertion and removing key-value pairs.
Queue is a special type of collection that
stores the elements in FIFO style (First In
First Out).

It contains the elements in the order they


were added.

Queue<T>
Elements can be added using the Enqueue()
method. Cannot use collection-initializer
syntax.

Elements can be rettieved using the


Dequeue() and the Peek() methods. It does
nor support an indexer.
Stack is a special type of collection
that stores elements in LIFO style
(Last In First Out).

Elements can be added usşng the


Stack<T> Push() method. Cannot use
collection-initializer syntax.

Elements can be retrieved using


the Pop() and the Peek() methods.
It does not support an indexer.
The classes of the System.Collections
namespace are listed below:
• ArrayList
• Stack
Non-Generic • Queue
Collections • SortedList
• Hashtable
The ArrayList is a non-
generic collection of
objects whose size
increases dynamically.
ArrayList
The ArrayList class
included in the
System.Collections
namespace.
Stack stores the values in LIFO style
(Last In First Out).

It provides a Push() method to add a


Stack value and Pop()&Peek() methods to
retrieve values.

C# includes both, generic and non-


generic Stack.
Queue stores the values in FIFO style (First In First
Out).

It keeps the order in which the values were added.

Queue It provides an Enqueue() method to add values


and a Dequeue() method to retrieve values from
the collection.

C# includes generic and non-generic Queue.


• The Hashtable is a non-generic collection
that stores key-value pairs, similar to generic
Dictionary<Tkey,Tvalue> collection.
• Keys must be unique and cannot be null.
Hashtable Values can be null or duplicate.
• Values can be accessed by passing
associated key in the indexer e.g.
myHashtable[key]

You might also like