You are on page 1of 74

Visual Programming

Introduction
History of C#

Version Date .NET Framework Visual Studio


C# 1.0 Jan-02 .NET Framework 1.0 Visual Studio .NET 2002
C# 1.2 Apr-03 .NET Framework 1.1 Visual Studio .NET 2003
C# 2.0 Nov-05 .NET Framework 2.0 Visual Studio 2005
C# 3.0 Nov-07 .NET Framework 2.0/3.0/3.5 Visual Studio 2008/2010
C# 4.0 Apr-10 .NET Framework 4 Visual Studio 2010
C# 5.0 Aug-12 .NET Framework 4.5 Visual Studio 2012/2013
C# 6.0 Jul-15 .NET Framework 4.6 Visual Studio 2015
C# 2.0
• Generics
• Partial types
• Anonymous methods
• Iterators
• Nullable types
• Static classes
• And more..
C# 3.0
• Implicitly typed local variables
• Object and collection initializers
• Auto-properties
• Extension methods
• Query expressions
• Lambda expressions
• Expression trees
• And more..
C# 4.0
• Dynamic binding
• Named and optional parameters
• Generic Variance
• COM Interoperability
• And more..
C# 5.0
• Asynchronous methods
• Caller info attributes
It’s all about Object
• The object type is an alias for Object in the
.NET Framework.
• All types, predefined and user-defined,
reference types and value types, inherit
directly or indirectly from Object.
• can assign values of any type to variables of
type object.
Object Class
“Every thing in C# is derived from Object class of Base class
library”
Access Name Description

Determines whether the specified object is equal to the current


public Equals(Object)
object.

Determines whether the specified object instances are


public static Equals(Object, Object) considered equal.

protected Finalize Allows an object to try to free resources and perform other
cleanup operations before it is reclaimed by garbage collection.

public GetHashCode Serves as a hash function for a particular type.

public GetType Gets the Type of the current instance.

protected MemberwiseClone Creates a shallow copy of the current Object.

public static ReferenceEquals Determines whether the specified Object instances are the same
instance.

public ToString Returns a string that represents the current object.


Shallow Copy
• Shallow copying is creating a new object and
then copying the non-static fields of the
current object to the new object. If the field is
a value type, a bit by bit copy of the field is
performed.
• If the field is a reference type, the reference is
copied but the referred object is not, therefore
the original object and its clone refer to the
same object.
Deep Copy
• Deep copying is creating a new object and then
copying the non-static fields of the current object
to the new object. If a field is a value type, a bit
by bit copy of the field is performed.
• If a field is a reference type, a new copy of the
referred object is performed. A deep copy of an
object is a new object with entirely new instance
variables, it does not share objects with the old.
Shallow and Deep copy
• MemberwiseClone method creates a shallow copy of the
current object. This function cannot be overridden.
Namespace Example
using System; //NESTED NAME SPACE or NAMESPACE HIERARCHY
class Test namespace Punjab
{ {
public static void Main(string[] args) class Lahore
{ {
Console.WriteLine("Hello World"); public static void Hello()
Hello(); {
Pakistan.Federal.Hello(); System.Console.WriteLine(“Hello
Pakistan.Punjab.Lahore.Hello(); Chief Minister!");
} }
static void Hello() }
{ class Rawalpindi
System.Console.WriteLine(“Directly {
Called"); public static void Hello()
} {
} System.Console.WriteLine(“Hello
namespace Pakistan Sheikh Rasheed!");
{ }
class Federal }
{ }
public static void Hello()
{
System.Console.WriteLine("Hello Prime
Minister!");
}
}
Using Statements for
Static Members
Using Statements for Static Members in a nutshell

class Program
{
static void Main(string[] args)
{
var angle = 90d;
Console.WriteLine(Math.Sin(angle));
}
}
Using Statements for Static Members in a nutshell

using System.Console;
using System.Math;

class Program
{
static void Main(string[] args)
{
var angle = 90d;
WriteLine(Sin(angle));
}
}
Types of Data Types
• All data types in C# are CTS (Common Type System) compliant.
• There are two types of data types in C#
• Value type (Stored on stack Memory, limited and fast access)
• Common Data types, structures
• Reference Type (Stored on heap, slow access)
• Classes, Arrays
• There are two ways to declare or define value type variables in
C#.

Examples: Primitive Data Types


System.Int32 x=0; //CTS compliant
int x1 = 0; //Using Alias, like c++
int p = new int(); //Another valid way, Initialized to 0
Types of Data Types
• Data types in .NET are specified by CTS. Language datatype maps to CTS datatype.
For example, int of C# maps to System.Int32 of CTS.
• CTS have two categories of types: Value Type and Reference Type
• Every type derived from System.Object. (Directly of Indirectly)
System.Object
• Data types are classes or structs that supports certain methods.
For example, string s = i.ToString();
• C# has 16 predefined types System.ValueType Reference Type

– 13 value types and CTS Types


– 3 reference types (string, dynamic, object) .
Value Types

Value Reference
Type Type
Value Type
• Value types store value on stack
• All value types are derived implicitly from the System.ValueType.
• Assigning one value type variable to another copies the actual value.
• While passing to function value types by default passes parameters by
value.
• 13 built-in value types are available (listed on next slide) System.Object

• User defined value type can be created using keywords:


– struct and
– enum System.ValueType

Value Types
Name CTS Type Description
sbyte System.SByte 8 bit signed integer
short System.Int16 16 bit signed integer
int System.Int32 32 bit signed integer
long System.Int64 64 bit signed integer
byte System.Byte 8 bit unsigned integer
ushort System.UInt16 16 bit unsigned integer
Uint System.UInt32 32 bit unsigned integer
ulong System.UInt64 64 bit unsigned integer
float System.Single 32 bit single precision floating point
double System.Double 64 bit single precision floating point
decimal System.Decimal 128 bit high precision decimal notation
bool System.Boolean Represents true of false
char System.Char Represents a single 1b bit character (Unicode)
Value Data Types List
Value Type
• Variables of reference types store actual data on heap and
references to the actual data on stack.
• The actual data stored on heap is referred as object.
• Assignment operation copies reference.
• While passing to function reference types by default passes
parameters by reference.
• Three build in reference types are available: string, dynamic
and object
• User defined reference type can be created using keywords:
– class
– Interface
– delegate
Operators in C#
Assignment in C#
Value Type
• Sizeof : Works just like C/C++ to find out the size of passed
parameter or data type in bytes. C# size of can only be used
in unsafe
• Typeof : “typeof” helps in checking the type of the class at
the runtime.
• Returns object of Type class that holds a lot of information
about type in question Look at members of Type class*
Structures in C#
• Structures can group program primitives like classes.
• C# structures are value types and are created on stack
• Members of structure are private in C# unlike C++ where they are public.
• Structures doesn’t support inheritance, they are implicitly sealed
• Stack operations are faster than heap operations
• Structures are some times used as light weight classes for faster
manipulation.
• Structures should be used wisely because they consume limited stack
space.
• All structures have Object as a base class and they can over-ride methods
of base class.
• Destructor and Finalize method can not be written for structures because
they are value types and have nothing to do with managed heap.
Structures in C#
Enumerations in C#
• An enumeration is a user defined integer type. When we declare
enumeration, we define a set of user defined values that are considered as a
domain for enumeration variable.
• One can use enumerations in function parameter or as a property of a class.
• Enumerations are there in C/C++ and other languages
• Enums help us to define a set of valid responses
• Can be passed in functions
Literals in C#
String: System.String
• Note: String is a reference type
Variables Declarations in C#
Box and Unbox
• Conversion from value type to reference type is known as boxing.
• Conversion from reference type to value type is un-boxing.
• A value can only be unboxed to the same data type only.

• By definition it is a process of storing value types on heap.


• When we define a new value type using structures, the .NET
framework implicitly supplies another class corresponding to value
class that helps us storing value types as reference types on heap
using boxing.
• Common data types and enumerations also have corresponding
classes.
static void Main(string[] args)
{
b 25
0
int a = 25; Unboxing
object o;
o = a; //boxing
Console.WriteLine("o = {0}", o.ToString()); 6743
null
o 6
25
67436
int b;
b = (int)o; //unboxing
Boxing
Console.WriteLine("b = {0}", b.ToString());
a 25

Console.ReadKey();
}

Stack Heap
Checked and Unchecked
• We can use checked block to make sure that variables do not
exceed their limits. Any overflow is detected using check block.
Unchecked, primarily used to allow overflow. Check is used when
overflow check is suppressed with compiler options and it is
explicitly enabled.
Type Conversions in C#
• There are two types of type conversions in C#.
• Implicit Conversions
– These conversions are performed by compiler for us, types with less bytes can
be converted into higher types (or higher number of bytes).
• Explicit Conversions
– This type of casting is performed just by using cast operators.
User Defined Casts
• User defined casts help us to cast between custom types. Our own classes and
structures.
• User defined casts are of two types just like predefined casts i.e.,
– Implicit Cast
– Explicit Cast
• There is a rule that you can not cast from base class to derived class.
• User defined casts are implemented in class or structure just like operator
overloading.
• create operator overloading functions to cast to different classes a same operator can
be functionally overloaded.
Coalesce (??), is and as operators
• ?? Returns first operand that is not null.
• Primary use of Coalesce operator is to assign a nullable type to non
nullable type.
• “is” is used to check if the object belongs to a specific type.
• “as” keyword works like cast operator except one difference that it results
in a null reference if cast fails and does not generate an exception. Only
compatible data types can be casted using as operator.
Pass by Value, Pass by Reference ?
Out and Ref
• Ref keyword is used to pass variables to a method by reference,
in general value type parameters are passed by copying data to
the method argument variables, remember reference types are
always passed by-ref, the same old law.
• Out keyword can be pre-fixed with a method parameter. The
keyword out is also used to pass value by reference with a slight
difference. The variable being passed as out does not need to
be initialized where as a variable being passed as a reference
must be initialized in the calling code. The variable sent as out
must be initialized by the called method, otherwise it will be
treated as an error.
• Both out and ref are treated similarly at the compile time. See
overloading constraints*
Out and Ref
All about Arrays in C#
• In C/C++ array is just pointer to memory address and index to an array is simply an offset from
that address. Because C/C++ do not track the size of the array therefore, there is nothing to
stop a program from referencing an element outside the bounds of an array.
• C# supports the array as a definite type. By treating arrays as objects with methods and
properties, the CLR is able to catch these kinds of out-of-bound errors. Remember C# arrays are
reference type (objects). Arrays in C# stick to data-structures definition of homogeneity and
indexing.

• C# arrays use indexes starting with 0.


• Arrays are allocated on heap by default and are reference type.
• Arrays of value types are initialized with 0.
• Arrays of reference types are initialized with null by default.
• Multi-dimensional arrays are supported.
• Jagged arrays i.e. arrays of arrays are supported.
• Either initialize all elements or no elements (this limitation is not there in C++)
• Arrays can be forced to be created on stack
• Following statement need Under-standing of foreach loop
• C# arrays are derived from Array class that implements IEnumerable interface
Arrays Example 1
Arrays Example 2
Arrays Out of Box
• Arrays support following methods, few things
are discussed here
Parameter Arrays
• These arrays are basically C# equivalent of ellipsis in
C/C++
• Parameter arrays allow us to pass in any number of
homogeneous or non-homogeneous parameters to a
function
Example: Parameter Arrays
The Loops

• All of following control constructs and control


statements work like c++. Therefore they are
just mentioned and their details are skipped
from this slide set.
– for loop
– while loop
– do-while loop
– break and continue
Control Flow: conditional (if)

• “if” statement of C# is just like C++


• Skipping else block is allowed
• Nested if-else are allowed
• If-else ladder can be developed
Control Flow: conditional (switch)
• To choose one flow path out of several
• Switch statement is like c/c++ except one difference that you must give
break statement after code in case.
• Nesting of switch statements isallowed and strings are also supported
Control Flow: Loop (foreach )
• “foreach” loop is not available in c/c++, it helps in traversing an array or
collection of objects. Only collections that support IEnumerable interface
are supported.
• It traverses elements one by one from start to end and internally maintain
index
• Value of an item in the collection being traversed can not be changed.
The using statement
• “Using” block ensures that a resource intensive
objects must be destroyed as soon as they are no
more required. The object should be
implementing IDisposable to be capable of being
used in using statement.
Try-catch-finally (Exceptions) -1
• Structured error handling is also implemented by C# using try-catch-finally
block.
• Supports nesting
• Base class for Exception objects is System. Exception
• There are three major types of exceptions
– Application Exceptions: Custom exceptions
– System Exceptions: Stack overflow, overflow
– IO Exceptions: File load exception
• Throw keyword is used to throw exception
– throw new My exception();
Try-catch-finally (Exceptions) -2
Naïve Example Exceptions
Destruction & Finalizers

• Finalize method is declared in Object class


• The destructor you write for C# is implicitly called by the
Finalize method.
• Destructor or finalize in C# is non-deterministic, it means
that you never know when it will be called. Its because
garbage collector de-allocates and calls the finalize which
calls destructor.
• The destructor takes no parameters and returns void
• Destructor de-allocates, cleans and closes un-managed
parts of program. For example if you have opened file or
database connection, you can grace-fully shut it down. But
it could cause synchronization problem in the program.
Class in C#
• Class a C# encapsulates member variables indexers, properties,
constructors, operators, delegates, events other classes and methods.
• C# classes support destructors and finalizers.
• But use of destructors is not recommended due to being non-
deterministic.
• Destructors can be overloaded
• For deterministic execution of some code Close or Dispose conventions
are used
Class in C#

• Tips
• Remember you can use private/protected with inner classes only
• You can not use private or protected at namespace level
• Namespace elements can not be explicitly declared as private, protected
or protected internal.
Partial Keyword & Class
• C# introduces a partial keyword that allow a single class to spanned across
several classes.
• These classes are merged into a single class during compilation.
• It helps in managing wizard generated code and custom code separately.
Inheritance
• In C# multiple Inheritance is not allowed.
• A class can inherit multiple interfaces.
• base is keyword in C# can be used to access the base class members
• Multiple inheritance cause complexity in program and compiler
• Multiple inheritance makes classes coupling incontrollable
• Multiple inheritance causes performance issues
Interface Concept

• Interfaces, like classes, define a set of properties, methods, and


events. But unlike classes, interfaces do not provide
implementation. They are implemented by classes, and defined as
separate entities from classes.

• An interface represents a contract. A class that implements an


interface must implement every aspect of that interface exactly as
it is defined.

• An interface can inherit one or more interfaces

• Interface serves as a contract of method signatures among classes.


• An interfaces helps in separating implementation from contract.
Interface Syntax in C#
• Syntax:
• [attributes] [modifiers] interfaceidentifier[:base-list] {interface-body}[;]
• Modifiers:new and for access specifies public, protected, private, internal
• An interface can be a member of a namespace or a class and can contain
signatures of methods, properties, indexers and events. We will learn
about last two a bit latter.
Class member method modifiers
Method Overloading
• OOP Concept of function overloading is supported by C# and
by .Net framework in general. A single class may contain
multiple implementations of same method that differ in
number and type of arguments.
Method Overriding in C#
• Method overriding allows to change the implementation of
base class method in derived class. The virtual and override
keyword play a vital role in achieving this objective. Look at
following example
Operator Overloading in C#
• Defines a new operator for a class
• Overloaded operators are required to perform arithmetic and comparison
operations on reference types.
• C# does not allow us to overload = operator
• If you overload +,-,/ or * then +=, -=, /= and *= are automatically overloaded
• Comparison operator can be overloaded (==, !=, > , >=, < and <=)
• But all of these operators are overloaded in pairs.
1. == and != (First override == and then !=)
2. > and >=
3. < and <=
Properties in C#
• C# provides special set and get accessor methods for getting
and setting the value of the property. This syntax is equivalent
to Get/Set methods.

class MyTime
{ public int Mintues
private int seconds; {
private int mintues; set { mintues = value; }
private int hours; }
//-------------------------------- //-----------------------------
- public int Hours
public int Seconds {
{ get { return hours; }
get { return seconds; } }
set { seconds = value; } }
}
How to use a Property?

class Program
{
static void Main()
{
MyTime time = new MyTime();

// Assigning the Hours property causes the 'set' accessor to be called.


time.Seconds = 30;
time.Mintues = 50;
time.Hours = 2;

// Evaluating the Hours property causes the 'get' accessor to be called.

System.Console.WriteLine("Time is: " +


time.Hours+":"+time.Mintues+":"+time.Seconds);
}
}
Auto-Property Initializers
Auto-property initializers in a nutshell

class Person
{
public string Name { get; set; }
}
class Person
{
public string Name { get; } = "Anonymous";
}
Auto-property initializers in a nutshell

class Person
{
public string Name { get; }

public Person()
{
Name = "Filip";
}
}
System.Collections Namespace

Class Description
Implements the IList interface using an array whose size is
ArrayList dynamically increased as required.
Manages a compact array of bit values, which are
represented as Booleans, where trueindicates that the bit is
BitArray on (1) and false indicates the bit is off (0).
Compares two objects for equivalence, ignoring the case of
CaseInsensitiveComparer strings.
Obsolete.Supplies a hash code for an object, using a hashing
CaseInsensitiveHashCodeProvider algorithm that ignores the case of strings.
Provides the abstract base class for a strongly typed
CollectionBase collection.
Compares two objects for equivalence, where string
Comparer comparisons are case-sensitive.
System.Collections Namespace

Class Description
Provides the abstract base class for a strongly typed collection of
DictionaryBase key/value pairs.
Represents a collection of key/value pairs that are organized based on
Hashtable the hash code of the key.
Provides the abstract base class for a strongly typed non-generic read-
ReadOnlyCollectionBase only collection.
Represents a collection of key/value pairs that are sorted by the keys
SortedList and are accessible by key and by index.
Represents a simple last-in-first-out (LIFO) non-generic collection of
Stack objects.
Provides objects for performing a structural comparison of two
StructuralComparisons collection objects.

You might also like