C# basics
Why do other coders wear glasses?
BECAUSE THEY DON’T C#
.NET platform building blocks
Locates, loads and manages .NET
objects taking care of memory
management, application hosting,
threads coordination, security
checks, etc.
• CLR supported types and constructs
• How they interact with each other
• Their representation (metadata)
Langs might not support some feature
Defines a subset of common types
and programming constructs that
all .NET programming languages
can agree on
Available to all .NET languages
Types that can be used to build
any type of software application
.NET assemblies
Type hierarchy
Intrinsic CTS data types
Default values
Variable definition
dataType variableName = variableValue;
var variableName = variableValue;
OR
Assembly, namespace, type
A namespace is the grouping of semantically related types contained in an
assembly or spread across multiple related assemblies
A single assembly can contain any number of namespaces, each of which can
contain any number of types
using System;
namespace Foo
{
public static class Bar
{
public static void Main()
{
Console.WriteLine("Hello world!");
}
}
}
Interacting with the console
Console.Write("Please enter your name: ");
var name = Console.ReadLine();
Console.Write("Please enter your age: ");
string age = Console.ReadLine();
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Hello {0}! You are {1} years old.", name, age);
Console.ForegroundColor = prevColor;
Formatting numbers
Code based learning
1. Core constructs
2. Encapsulation
3. Inheritance and polymorphism
4. Exceptions
5. Interfaces
http://github.com/luigiberrettini/c-sharp-basics
Managed / Unmanaged
Managed
• Native to the framework
• Any class compiled to .NET IL
Unmanaged
• Not native to the framework
• Anything obtained from the OS or a third party non-.NET dll
Managed Resource (e.g. SqlConnection)
• Any piece of memory or file or pointer neatly wrapped in a .NET object
• Cleaned up by the CLR if not cleaned by programmers
Unmanaged Resource (e.g. window handle)
• Any piece of memory or file or pointer that you have a direct reference to
(obtained calling the API of the OS using Platform Invocation Services i.e. PInvoke
or as a result of some very elaborate COM interoperability scenarios)
• Not cleaned up by the CLR, unless its class implements at least a Finalizer
Managed heap
• Small Object Heap
• Large Object Heap
Managed heap
The CLR takes care of the managed heap without
direct intervention through the garbage collector
Finalize
public class Object
{
//...
protected virtual void Finalize() {}
//...
}
• If manipulating memory that the CLR cannot manage:
classes using unmanaged resources (Pinvoke, COM, Marshal)
• To be avoided in other cases since it takes time
• The CLR, before removing an object from memory, calls it:
 during natural garbage collections
 on GC.Collect()
 when the application domain hosting the application is unloaded from memory
Next object pointer
Address of the next object that will be created
Object creation
• Calculate amount of memory required for the object
• Check if managed heap has enough room to host the object
• If not enough memory → garbage collection (free up memory)
• Call the constructor
• Advance the next object pointer
• If object overrides Finalize:
 mark it as finalizable
 store a pointer to it on the finalization queue
Garbage marking
• CLR builds an object graph of reachable objects on the heap
(assigning null to a reference does not force the GC to run)
• Each object is graphed only once (circular reference handling)
• Unreachable objects are marked as garbage
Garbage sweeping
• Non-finalizable marked objects are swept from memory
• Finalizable marked objects are copied off the heap to the
F-reachable queue (finalization reachable queue)
• On next garbage collection, a separate thread will invoke the
Finalize() method for objects on the F-reachable queue
(2 GC run to truly finalize an object)
• The heap is compacted
• Pointers are updated
• Next object pointer is adjusted
Finalizable objects queues
Generations
• The longer an object has existed on the heap, the more likely it is to stay there
• Most recently created objects are likely to be unreachable rather quickly
Each object on the heap belongs to one of the following generations
• Generation 0 (ephemeral generation)
Newly allocated SOH objects that has never been marked for collection
• Generation 1 (ephemeral generation)
SOH objects that survived a garbage collection
(marked for collection but not removed because enough heap space was acquired)
• Generation 2
 SOH objects that survived more GC sweeps
 LOH objects
Garbage collection
1. Investigate all generation N objects
2. Collect all the required memory
3. If enough memory freed
Not collected (survived) objects are promoted to generation N+1 (up to gen 2)
4. If additional memory still required
Repeat steps 1 to 3 with generation N+1 objects
GC flavors
Concurrent garbage collection (before .NET 4.0)
• During a collection for ephemeral generations the GC suspends all active
threads within the current process to block any access to the heap
• Generation 2 objects are cleaned up on a dedicated thread without suspending
active threads and objects allocation
Background garbage collection (with .NET 4.0 and above)
During a collection for non-ephemeral generation, the GC is able to collect objects
on ephemeral generations using a dedicated background thread
IDisposable and the dispose pattern
Dispose pattern = Dispose + Finalize
Only with unmanaged code (it concerns about P/Invoke, handles, IntPtr and so far)
IDisposable = Dispose only
In all the other cases to let the consumer of a class release the resource ASAP
(use the using block whenever possible)
IDisposable implementers
• managed resources
• should be Disposed manually (not needed anymore) or in the consumer’s Dispose
Non‒IDisposable implementers
• managed resources managed directly by the GC
• the only thing you can do is setting the reference to null (XmlDocument)
Joe Duffy
Peter Bromberg

C# basics

  • 1.
  • 2.
    Why do othercoders wear glasses? BECAUSE THEY DON’T C#
  • 3.
    .NET platform buildingblocks Locates, loads and manages .NET objects taking care of memory management, application hosting, threads coordination, security checks, etc. • CLR supported types and constructs • How they interact with each other • Their representation (metadata) Langs might not support some feature Defines a subset of common types and programming constructs that all .NET programming languages can agree on Available to all .NET languages Types that can be used to build any type of software application
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
    Variable definition dataType variableName= variableValue; var variableName = variableValue; OR
  • 9.
    Assembly, namespace, type Anamespace is the grouping of semantically related types contained in an assembly or spread across multiple related assemblies A single assembly can contain any number of namespaces, each of which can contain any number of types using System; namespace Foo { public static class Bar { public static void Main() { Console.WriteLine("Hello world!"); } } }
  • 10.
    Interacting with theconsole Console.Write("Please enter your name: "); var name = Console.ReadLine(); Console.Write("Please enter your age: "); string age = Console.ReadLine(); ConsoleColor prevColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Hello {0}! You are {1} years old.", name, age); Console.ForegroundColor = prevColor;
  • 11.
  • 12.
    Code based learning 1.Core constructs 2. Encapsulation 3. Inheritance and polymorphism 4. Exceptions 5. Interfaces http://github.com/luigiberrettini/c-sharp-basics
  • 13.
    Managed / Unmanaged Managed •Native to the framework • Any class compiled to .NET IL Unmanaged • Not native to the framework • Anything obtained from the OS or a third party non-.NET dll Managed Resource (e.g. SqlConnection) • Any piece of memory or file or pointer neatly wrapped in a .NET object • Cleaned up by the CLR if not cleaned by programmers Unmanaged Resource (e.g. window handle) • Any piece of memory or file or pointer that you have a direct reference to (obtained calling the API of the OS using Platform Invocation Services i.e. PInvoke or as a result of some very elaborate COM interoperability scenarios) • Not cleaned up by the CLR, unless its class implements at least a Finalizer
  • 14.
    Managed heap • SmallObject Heap • Large Object Heap Managed heap The CLR takes care of the managed heap without direct intervention through the garbage collector
  • 15.
    Finalize public class Object { //... protectedvirtual void Finalize() {} //... } • If manipulating memory that the CLR cannot manage: classes using unmanaged resources (Pinvoke, COM, Marshal) • To be avoided in other cases since it takes time • The CLR, before removing an object from memory, calls it:  during natural garbage collections  on GC.Collect()  when the application domain hosting the application is unloaded from memory
  • 16.
    Next object pointer Addressof the next object that will be created
  • 17.
    Object creation • Calculateamount of memory required for the object • Check if managed heap has enough room to host the object • If not enough memory → garbage collection (free up memory) • Call the constructor • Advance the next object pointer • If object overrides Finalize:  mark it as finalizable  store a pointer to it on the finalization queue
  • 18.
    Garbage marking • CLRbuilds an object graph of reachable objects on the heap (assigning null to a reference does not force the GC to run) • Each object is graphed only once (circular reference handling) • Unreachable objects are marked as garbage
  • 19.
    Garbage sweeping • Non-finalizablemarked objects are swept from memory • Finalizable marked objects are copied off the heap to the F-reachable queue (finalization reachable queue) • On next garbage collection, a separate thread will invoke the Finalize() method for objects on the F-reachable queue (2 GC run to truly finalize an object) • The heap is compacted • Pointers are updated • Next object pointer is adjusted
  • 20.
  • 21.
    Generations • The longeran object has existed on the heap, the more likely it is to stay there • Most recently created objects are likely to be unreachable rather quickly Each object on the heap belongs to one of the following generations • Generation 0 (ephemeral generation) Newly allocated SOH objects that has never been marked for collection • Generation 1 (ephemeral generation) SOH objects that survived a garbage collection (marked for collection but not removed because enough heap space was acquired) • Generation 2  SOH objects that survived more GC sweeps  LOH objects
  • 22.
    Garbage collection 1. Investigateall generation N objects 2. Collect all the required memory 3. If enough memory freed Not collected (survived) objects are promoted to generation N+1 (up to gen 2) 4. If additional memory still required Repeat steps 1 to 3 with generation N+1 objects
  • 23.
    GC flavors Concurrent garbagecollection (before .NET 4.0) • During a collection for ephemeral generations the GC suspends all active threads within the current process to block any access to the heap • Generation 2 objects are cleaned up on a dedicated thread without suspending active threads and objects allocation Background garbage collection (with .NET 4.0 and above) During a collection for non-ephemeral generation, the GC is able to collect objects on ephemeral generations using a dedicated background thread
  • 24.
    IDisposable and thedispose pattern Dispose pattern = Dispose + Finalize Only with unmanaged code (it concerns about P/Invoke, handles, IntPtr and so far) IDisposable = Dispose only In all the other cases to let the consumer of a class release the resource ASAP (use the using block whenever possible) IDisposable implementers • managed resources • should be Disposed manually (not needed anymore) or in the consumer’s Dispose Non‒IDisposable implementers • managed resources managed directly by the GC • the only thing you can do is setting the reference to null (XmlDocument) Joe Duffy Peter Bromberg