You are on page 1of 54

C# FOR UNITY -

ARCHITECTURE & DATA


PRESENTER: DUONG HOANG THANH
CONTENTS

.NET Framework
Unity Player Architecture
Value and Reference Types
C# Collections
C# Generics
.NET PLATFORM
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)
.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.
.NET
ARCHITECTURE

Consists of
Common Language Runtime
.NET Framework Class
Library.
.NET
FRAMEWORK
HISTORY
.NET FOR UNITY
Unity supports .NET framework 3.5 (Subset)
with CLR 2.0
and C# 4 (Subset)

Unity Road Map: .NET


profiler 4.6 upgrade is in
research
C# FOR UNITY

Unity supports
C# 4.0 (Subset)
.NET COMPILATION AND EXECUTION
Bytecode Native Code
Source Code

C# COMPILER COMPILED INTO NATIVE CODE


M
S
I EXECUTION OF CODE
VB COMPILER L

Compile Time Runtime


UNITY PLAYER ARCHITECTURE
UNITY PLAYER ARCHITECTURE

Unity Player Mono Project


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
VALUE AND REFERENCE TYPES
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
VALUE TYPES

All numeric data types


Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations
REFERENCE TYPES

String
All arrays, even if their elements are value types
Class types, such as Form
Delegates
STRUCT VS CLASS

Struct Class
Value type Reference type
Usually used for smaller amounts Usually used for large amounts of
of data data
Does not support Inheritance Support Inheritance
Cannot have Destructor Can have Destructor
Passed to method by value Passed to method by reference
STRUCT VS CLASS

Struct Class
Cannot contain explicit Can create explicit parameterless
parameterless constructors in class
Can not instance Field initializer Can instance Field initializer
Can not be garbage collector so Can be garbage collector because
no memory management. garbage collector works on heap
memory
BOXING & UNBOXING
BOXING - UNBOXING PERFORMANCE
C# COLLECTIONS
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.
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.
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.
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;
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)
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;
...
}
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;
...
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;
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();
...
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);
}
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;

QUEUE<T>, STACK<T>

Implemented by array
private T[] _array;
Default capacity is 4
Go double each time expanding capacity
remove insert at remove Random In-order Search for
add to end Notes
from end middle from middle Access Access specific element

Most efficient use of memory;


Array O(n) O(n) O(n) O(n) O(1) O(1) O(n) use in cases where data size is
fixed.
Implementation is optimized
best case O(1);
List<T> O(1) O(n) O(n) O(1) O(1) O(n) for speed. In many cases, List
worst case O(n)
will be the best choice.

best case O(1); List is a better choice, unless


Collection<T> O(1) O(n) O(n) O(1) O(1) O(n)
worst case O(n) publicly exposed as API.

Many operations are fast,


LinkedList<T> O(1) O(1) O(1) O(1) O(n) O(1) O(n) but watch out for cache
coherency.
Shouldn't be selected for
best case O(1);
Stack<T> O(1) N/A N/A N/A N/A N/A performance reasons, but
worst case O(n)
algorithmic ones.
Shouldn't be selected for
best case O(1);
Queue<T> O(1) N/A N/A N/A N/A N/A performance reasons, but
worst case O(n)
algorithmic ones.
Although in-order access time
is constant time, it is usually
best case O(1); best case O(1);
Dictionary<K,T> O(1) O(1) O(1)* O(1)* O(1) slower than other structures
worst case O(n) worst case O(n)
due to the over-head of looking
up the key.
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.
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.
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.
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.
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.
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.
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.
C# GENERICS
// Declare the generic class.
public class GenericList<T>
{
void Add(T input) { }
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,
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.
GENERICS IN RUNTIME Specialized version Instances

// Stack of references types


Stack<int> stackOne = new Stack<int>(); stackOne
Stack<int> stackTwo = new Stack<int>(); class Stack<int>
stackTwo

Stack<long> stackThree = new Stack<long>(); class Stack<long> stackThree

class Customer { }
class Order { }
// Stack of value types
Stack<Customer> customers;
Stack<Order> orders = new Stack<Order>(); customers
class Stack<T>
customers = new Stack<Customer>(); others
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()
{
// ...
}
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.
GENERICS VARIANCES

Covariance: Enables you to use a more derived type than originally specified
IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;
Contravariance: Enables you to use a more generic (less derived) type than originally
specified.
Action<Base> b = (target) => { };
Action<Derived> d = b;
Invariance: Means that you can use only the type originally specified
DEFINE GENERICS VARIANCES

A covariant type parameter is marked with the out keyword


public interface IEnumerable<out T> : IEnumerable
A contravariant type parameter is marked with the in keyword
public delegate void Action<in T>(
T obj
)
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);
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>();
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/)
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