SlideShare uma empresa Scribd logo
1 de 63
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
C# COMPILER
VB COMPILER
M
S
I
L
COMPILED INTO NATIVE CODE
EXECUTION OF CODE
Compile Time Runtime
Source Code
Bytecode Native Code
IL2CPP
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
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
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
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.
HashSet<T>
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
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.
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
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) { }
}
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
// 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
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.
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>();
VARIANCES
COVARIANCE AND CONTRAVARIANCE
COVARIANCE AND CONTRAVARIANCE
COVARIANCE AND CONTRAVARIANCE
COVARIANCE AND CONTRAVARIANCE
SAFE COVARIANCE
SAFE CONTRAVARIANCE
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
VARIANCE IN .NET 4.0
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

Mais conteúdo relacionado

Mais procurados

Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
Hemant Jain
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
Eelco Visser
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
Hariz Mustafa
 

Mais procurados (20)

Stl (standard template library)
Stl (standard template library)Stl (standard template library)
Stl (standard template library)
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Python by ganesh kavhar
Python by ganesh kavharPython by ganesh kavhar
Python by ganesh kavhar
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Type Casting C# - Lec4 (Workshop on C# Programming: Learn to Build)
Type Casting C# - Lec4 (Workshop on C# Programming: Learn to Build)Type Casting C# - Lec4 (Workshop on C# Programming: Learn to Build)
Type Casting C# - Lec4 (Workshop on C# Programming: Learn to Build)
 
C# Basic - Lec1 (Workshop on C# Programming: Learn to Build)
C# Basic - Lec1 (Workshop on C# Programming: Learn to Build)C# Basic - Lec1 (Workshop on C# Programming: Learn to Build)
C# Basic - Lec1 (Workshop on C# Programming: Learn to Build)
 
Data Type C# - Lec2 (Workshop on C# Programming: Learn to Build)
Data Type C# - Lec2 (Workshop on C# Programming: Learn to Build)Data Type C# - Lec2 (Workshop on C# Programming: Learn to Build)
Data Type C# - Lec2 (Workshop on C# Programming: Learn to Build)
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
 
Generics C#
Generics C#Generics C#
Generics C#
 
Generics past, present and future
Generics  past, present and futureGenerics  past, present and future
Generics past, present and future
 
Getting Started with R
Getting Started with RGetting Started with R
Getting Started with R
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Net framework
Net frameworkNet framework
Net framework
 

Semelhante a CSharp for Unity - Day 1

What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?
ukdpe
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
jorgesimao71
 
UNIT-I.pptx of subject in engineering bla bla bla
UNIT-I.pptx of subject in engineering bla bla blaUNIT-I.pptx of subject in engineering bla bla bla
UNIT-I.pptx of subject in engineering bla bla bla
SEN150VAIBHAVWAKHARE
 

Semelhante a CSharp for Unity - Day 1 (20)

Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Database Sizing
Database SizingDatabase Sizing
Database Sizing
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?What's New for Developers in SQL Server 2008?
What's New for Developers in SQL Server 2008?
 
SQL Server 2008 Overview
SQL Server 2008 OverviewSQL Server 2008 Overview
SQL Server 2008 Overview
 
Introduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaIntroduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKenna
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
C
CC
C
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
1. python programming
1. python programming1. python programming
1. python programming
 
Shivam PPT.pptx
Shivam PPT.pptxShivam PPT.pptx
Shivam PPT.pptx
 
Introduction to R _IMPORTANT FOR DATA ANALYTICS
Introduction to R _IMPORTANT FOR DATA ANALYTICSIntroduction to R _IMPORTANT FOR DATA ANALYTICS
Introduction to R _IMPORTANT FOR DATA ANALYTICS
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptx
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Next .NET and C#
Next .NET and C#Next .NET and C#
Next .NET and C#
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
 
UNIT-I.pptx of subject in engineering bla bla bla
UNIT-I.pptx of subject in engineering bla bla blaUNIT-I.pptx of subject in engineering bla bla bla
UNIT-I.pptx of subject in engineering bla bla bla
 
DS.pptx
DS.pptxDS.pptx
DS.pptx
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 

Último

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Último (20)

tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

CSharp for Unity - Day 1

  • 1. C# FOR UNITY - ARCHITECTURE & DATA PRESENTER: DUONG HOANG THANH
  • 2. CONTENTS • .NET Framework • Unity Player Architecture • Value and Reference Types • C# Collections • C# Generics
  • 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.
  • 6. .NET ARCHITECTURE Consists of • Common Language Runtime • .NET Framework Class Library.
  • 8. .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
  • 9. C# FOR UNITY Unity supports C# 4.0 (Subset)
  • 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
  • 13. UNITY PLAYER ARCHITECTURE Unity Player Mono Project
  • 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
  • 22. BOXING - UNBOXING PERFORMANCE
  • 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; …
  • 35. QUEUE<T>, STACK<T> • Implemented by array private T[] _array; • Default capacity is 4 • Go double each time expanding capacity
  • 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>();
  • 55.
  • 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