4. WHAT IS .NET FRAMEWORK?
• SDK: A technology that supports building and running the next generation of
applications and XML Web services.
• Runtime: A managed execution environment that provides a variety of services
to its running applications:
• Memory management.
• A common type system
• An extensive class library.
• Development frameworks and technologies (ASP.NET, ADO.NET, WCF…)
• Language interoperability (CIL)
• Version compatibility.
• Side-by-side execution.
• Multitargeting (Windows, Windows Phone, Xbox…)
5. .NET OBJECTIVES
• Provide a consistent object-oriented programming environment.
• Provide a code-execution environment that
• Minimizes software deployment and versioning conflicts.
• Promotes safe execution of code.
• Eliminates performance problems of scripted or interpreted environments.
• Make developer experience consistent across widely varying types of
applications.
• Ensure that code based on the .NET Framework can integrate with any other
code.
10. .NET COMPILATION AND EXECUTION
C# COMPILER
VB COMPILER
M
S
I
L
COMPILED INTO NATIVE CODE
EXECUTION OF CODE
Compile Time Runtime
Source Code
Bytecode Native Code
14. MONO FOR ANDROID
• Use C# as development language
• Use .NET base class library
• Can be developed using Visual Studio or
MonoDevelop as an IDE
• Code will compiled into Mono IL
• Can be interop between Dalvik and
mono via Mono Callable Wrapper and
Android Callable Wrapper
16. C# DATA TYPES
• Value types:
Holds the data within its own memory
allocation
• Reference types:
Contains a pointer to another memory
location that holds the data.
Static memory Dynamic memory
17. VALUE TYPES
• All numeric data types
• Boolean, Char, and Date
• All structures, even if their members are reference types
• Enumerations
18. REFERENCE TYPES
• String
• All arrays, even if their elements are value types
• Class types, such as Form
• Delegates
19. STRUCT VS CLASS
Struct Class
Value type Reference type
Usually used for smaller amounts
of data
Usually used for large amounts of
data
Does not support Inheritance Support Inheritance
Cannot have Destructor Can have Destructor
Passed to method by value Passed to method by reference
20. STRUCT VS CLASS
Struct Class
Cannot contain explicit
parameterless constructors
Can create explicit parameterless
in class
Can not instance Field initializer Can instance Field initializer
Can not be garbage collector so
no memory management.
Can be garbage collector because
garbage collector works on heap
memory
24. SYSTEM.COLLECTIONS.GENERIC
Class Description
Dictionary<TKey, TValue> Collection of key/value pairs that are organized based on
the key.
List<T> List of objects that can be accessed by index. Provides
methods to search, sort, and modify lists.
Queue<T> FIFO collection of objects.
SortedList<TKey, TValue> Collection of key/value pairs that are sorted by key based
on the associated IComparer<T> implementation.
Stack<T> LIFO collection of objects.
HashSet<T>
25. SYSTEM.COLLECTIONS
Class Description
ArrayList Array of objects whose size is dynamically increased as required.
Hashtable Collection of key/value pairs that are organized based on the hash
code of the key
Queue FIFO collection of objects.
Stack LIFO collection of objects.
26. SYSTEM.COLLECTIONS.SPECIALIZED
Class Description
HybridDictionary Implements IDictionary by using a ListDictionary is small, and
then switching to a Hashtable when gets large.
ListDictionary Implements IDictionary using a singly linked list (< 10 items.)
NameValueCollection Represents a collection of associated String keys and String
values that can be accessed either with the key or index.
OrderedDictionary Collection of key/value pairs that are accessible by key or index.
StringCollection Represents a collection of strings.
StringDictionary Implements a hash table with the key and the value strongly
typed to be strings rather than objects.
BitVector32 Provides a simple structure that stores Boolean values and small
integers in 32 bits of memory.
27. LIST<T>
• A variable-size List that uses an array of objects to store the elements.
• A List has a capacity, which is the allocated length of the internal array.
private const int _defaultCapacity = 4;
private T[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
28. LIST<T>
• The list is initially empty and has a capacity of zero.
static readonly T[] _emptyArray = new T[0];
public List() {
_items = _emptyArray;
}
• Construct a List with a given initial capacity.
public List(int capacity)
• Construct a List, copying the contents of the given collection. The size and capacity will
both be equal to the size of the given collection.
public List(IEnumerable<T> collection)
29. LIST<T>
• Adds the given object to the end of this list. The size of the list is increased by
one. If required, the capacity of the list is doubled before adding the new
element.
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
...
}
30. LIST<T>
• Upon adding the first element to the list the capacity is increased to 4, and then
increased in multiples of two as required.
• If the current capacity of the list is less than min, the capacity is increased to
twice the current capacity or to min, whichever is larger.
private const int _defaultCapacity = 4;
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0?
_defaultCapacity : _items.Length * 2;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
...
31. DICTIONARY<TKEY, TVALUE>
• Purpose: Generic hash table implementation
private struct Entry {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] buckets;
private Entry[] entries;
32. DICTIONARY<TKEY, TVALUE>
• Dictionary size will be expanded on demand
public void Add(TKey key, TValue value) {
Insert(key, value, true);
}}
private void Insert(TKey key, TValue value, bool add) {
if (buckets == null) Initialize(0);
...
if (count == entries.Length)
{
Resize();
...
33. DICTIONARY<TKEY, TVALUE>
• Entry size will be expanded to the prime number that greater than twice of
old size.
private void Resize() {
Resize(HashHelpers.ExpandPrime(count), false);
}
// (HashHelpers) Returns size of hashtable to grow to.
public static int ExpandPrime(int oldSize)
{
int newSize = 2 * oldSize;
return GetPrime(newSize);
}
34. DICTIONARY<TKEY, TVALUE>
• Array will be cloned and rehashed each time resizing
private void Resize(int newSize, bool forceNewHashCodes) {
int[] newBuckets = new int[newSize];
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
…
for (int i = 0; i < count; i++) {
if (newEntries[i].hashCode >= 0) {
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
…
36. add to end
remove
from end
insert at
middle
remove
from middle
Random
Access
In-order
Access
Search for
specific element
Notes
Array O(n) O(n) O(n) O(n) O(1) O(1) O(n)
Most efficient use of memory;
use in cases where data size is
fixed.
List<T>
best case O(1);
worst case O(n)
O(1) O(n) O(n) O(1) O(1) O(n)
Implementation is optimized
for speed. In many cases, List
will be the best choice.
Collection<T>
best case O(1);
worst case O(n)
O(1) O(n) O(n) O(1) O(1) O(n)
List is a better choice, unless
publicly exposed as API.
LinkedList<T> O(1) O(1) O(1) O(1) O(n) O(1) O(n)
Many operations are fast,
but watch out for cache
coherency.
Stack<T>
best case O(1);
worst case O(n)
O(1) N/A N/A N/A N/A N/A
Shouldn't be selected for
performance reasons, but
algorithmic ones.
Queue<T>
best case O(1);
worst case O(n)
O(1) N/A N/A N/A N/A N/A
Shouldn't be selected for
performance reasons, but
algorithmic ones.
Dictionary<K,T>
best case O(1);
worst case O(n)
O(1)
best case O(1);
worst case O(n)
O(1) O(1)* O(1)* O(1)
Although in-order access time
is constant time, it is usually
slower than other structures
due to the over-head of looking
up the key.
37. SELECTING A COLLECTION CLASS
Do you need a sequential list where the element is typically discarded after its
value is retrieved?
Yes:
• Consider using the Queue class or the Queue<T> generic class if you need first-in, first-
out (FIFO) behavior.
• Consider using the Stack class or the Stack<T> generic class if you need last-in, first-out
(LIFO) behavior.
No: consider using the other collections.
38. SELECTING A COLLECTION CLASS
Do you need to access the elements in a certain order, such as FIFO, LIFO, or
random?
• The Queue class and the Queue<T> generic class offer FIFO access.
• The Stack class and the Stack<T> generic class offer LIFO access.
• The LinkedList<T> generic class allows sequential access either from the head to the tail,
or from the tail to the head.
39. SELECTING A COLLECTION CLASS
Do you need to access each element by index?
• The ArrayList and StringCollection classes and the List<T> generic class offer access to
their elements by the zero-based index of the element.
• The Hashtable, SortedList, ListDictionary, and StringDictionary classes, and the
Dictionary<TKey, TValue> and SortedDictionary<TKey, TValue> generic classes offer
access to their elements by the key of the element.
• The NameObjectCollectionBase and NameValueCollection classes, and the
KeyedCollection<TKey, TItem> and SortedList<TKey, TValue> generic classes offer access
to their elements by either the zero-based index or the key of the element.
40. SELECTING A COLLECTION CLASS
Will each element contain one value, a combination of one key and one value,
or a combination of one key and multiple values?
• One value: Use any of the collections based on the IList interface or the IList<T> generic
interface.
• One key and one value: Use any of the collections based on the IDictionary interface or
the IDictionary<TKey, TValue> generic interface.
• One value with embedded key: Use the KeyedCollection<TKey, TItem> generic class.
• One key and multiple values: Use the NameValueCollection class.
41. SELECTING A COLLECTION CLASS
Do you need to sort the elements differently from how they were entered?
• The Hashtable class sorts its elements by their hash codes.
• The SortedList class and the SortedDictionary<TKey, TValue> and SortedList<TKey,
TValue> generic classes sort their elements by the key, based on implementations of the
IComparer interface and the IComparer<T> generic interface.
• ArrayList provides a Sort method that takes an IComparer implementation as a
parameter. Its generic counterpart, the List<T> generic class, provides a Sort method that
takes an implementation of the IComparer<T> generic interface as a parameter.
42. SELECTING A COLLECTION CLASS
• Do you need fast searches and retrieval of information?
• ListDictionary is faster than Hashtable for small collections (10 items or fewer).
• The Dictionary<TKey, TValue> generic class provides faster lookup than the
SortedDictionary<TKey, TValue> generic class.
43. SELECTING A COLLECTION CLASS
• Do you need collections that accept only strings?
• StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the
System.Collections.Specialized namespace.
• In addition, you can use any of the generic collection classes in the
System.Collections.Generic namespace as strongly typed string collections by specifying
the String class for their generic type arguments.
45. C# GENERICS
• Introduce concept of type parameters,
• which make it possible to design classes and methods
• that defer the specification of one or more types
• until the class or method is declared and instantiated by client code.
• For example,
• by using a generic type parameter T
• you can write a single class that other client code can use
• without incurring the cost or risk of runtime casts or boxing operations,
// Declare the generic class.
public class GenericList<T>
{
void Add(T input) { }
}
46. C# GENERICS
• To maximize code reuse, type safety, and performance.
• The most common use of generics is to create collection classes.
• You can create your own generic interfaces, classes, methods, events and
delegates.
• Generic classes may be constrained to enable access to methods on particular
data types.
• Information on the types that are used in a generic data type may be obtained
at run-time by using reflection.
47. GENERICS IN RUNTIME
// Stack of references types
Stack<int> stackOne = new Stack<int>();
Stack<int> stackTwo = new Stack<int>();
stackOne
stackTwo
class Customer { }
class Order { }
// Stack of value types
Stack<Customer> customers;
Stack<Order> orders = new Stack<Order>();
customers = new Stack<Customer>();
customers
others
Stack<long> stackThree = new Stack<long>(); stackThree
class Stack<int>
class Stack<long>
class Stack<T>
Specialized version Instances
48. GENERIC CONSTRAINTS
• By constraining the type parameter,
• you increase the number of allowable operations and method calls
• to those supported by the constraining type
• and all types in its inheritance hierarchy.
class EmployeeList<T>
where T: Employee, IEmployee, System.IComparable<T>, new()
{
// ...
}
49. GENERIC CONSTRAINTS
Constraint Description
where T: struct Must be a value type
where T : class Must be a reference type
where T : new() Must have a public parameterless constructor.
When used together with other constraints, the
new() constraint must be specified last.
where T : <base class name> Must be or derive from the specified base class.
where T : <interface name> Must be or implement the specified interface.
where T : U Supplied for T must be or derive from the argument
supplied for U.
50. GENERIC SINGLETON
public abstract class AppSingletonMono<T> : MonoBehaviour
where T : MonoBehaviour
{
private static T singleton;
protected virtual void Awake()
{
if (singleton == null || singleton == this)
{
singleton = (T)(MonoBehaviour)this;
DontDestroyOnLoad(transform.root);
51. GENERIC SINGLETON
public static T instance {
get {
if (singleton == null) {
singleton = (T)FindObjectOfType(typeof(T));
if (singleton == null) {
GameObject obj = new GameObject();
obj.name = "[@" + typeof(T).Name + "]";
singleton = obj.AddComponent<T>();
60. VARIANCE IN C# 4.0
• Supported for generic interface and delegate types only.
• Verified/enforced staticaliy in the definition.
• Value types are always invariant
• IEnumerable<int> is not IEnumerable<object>
• Similar to existing rules for arrays
• ref and out parameters need invariant types
62. REFERENCES
• Overview of the .NET Framework, Microsoft Developer Network (https://msdn.microsoft.com/en-
us/library/zw4w595w(v=vs.110).aspx)
• CLR C# and dot net version comparison chart, Anil Kumar, Mar 22 2013 (http://www.c-
sharpcorner.com/blogs/clr-c-sharp-and-dot-net-version-comparison-chart1)
• Develop android application with mono for android, Nicko Satria Utama, Aug 3, 2012
(http://www.slideshare.net/nickotech2000/develop-android-application-with-mono-for-android)
• Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing, Shivprasad
koirala, 14 May 2012 (https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-
value-types)
• Collections (C#), Microsoft Developer Network, July 20, 2015 (https://msdn.microsoft.com/en-
us/library/mt654013.aspx)
• .NET framework 4.6.2 reference source, Microsoft (https://referencesource.microsoft.com/)
63. REFERENCES
• Generics (C# Programming Guide), (https://docs.microsoft.com/en-
us/dotnet/articles/csharp/programming-guide/generics/)
• Selecting a Collection Class, Microsoft Developer Network
(https://msdn.microsoft.com/en-us/library/6tc79sx1.aspx)
• Manning Publication, C# in depth, Third Edition, Jon Skeet, 2014