Lecture 3
Lecture 3
Introduction
History of C#
protected Finalize Allows an object to try to free resources and perform other
cleanup operations before it is reclaimed by garbage collection.
public static ReferenceEquals Determines whether the specified Object instances are the same
instance.
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#.
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
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.
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.
• 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
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();
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.