distribution and integration technologiesapm/tdin/docs/03csharp.pdf · a delegate is a type...
TRANSCRIPT
Distribution and Integration
Technologies
C# Language
Some aspects of the C# Language 2
C#
❖A C# program is a collection of:▪ Classes
▪ Structs
▪ Interfaces
▪ Delegates
▪ Enums
▪ One entry point (static int Main(string[ ] args))
C C++
Java
C#
C++.NET
(can be grouped in namespaces)
Some aspects of the C# Language 3
CTS type intrinsic C# type (defined by a keyword)
System.SByte sbyte (8 bits)
System.Byte byte (8 bits)
System.Int16 short (16 bits)
System.UInt16 ushort (16 bits)
System.Int32 int (32 bits)
System.UInt32 uint (32 bits)
System.Int64 long (64 bits)
System.UInt64 ulong (64 bits)
System.Char char (unicode)
System.Single float (32 bits)
System.Double double (64 bits)
System.Boolean bool (true/false)
System.Decimal decimal (128 bits - fixed point)
System.Object object
System.String string
System.Array [ ]
C# Types
Naming Conventions
Some aspects of the C# Language 4
CasingWords are capitalized (z.B. ShowDialog)
First letter in upper case, except for local variables, private fields and constants
constants upper case SIZE, MAX_VALUElocal variables lower case i, top, sumprivate fields lower case data, lastElementpublic fields upper case Width, BufferLengthproperties upper case Length, FullNameenumeration constants upper case Red, Bluemethods upper case Add, IndexOftypes upper case StringBuilder (predefined types in lower case: int, string)namespaces upper case System, Collections
First wordNames of void methods should start with a verb (e.g. GetHashCode)
Other names should start with a noun (e.g. size, IndexOf, Collections)
Enumeration constants or bool members may start with an adjective (Red, Empty)
Operators and Statements
Some aspects of the C# Language 5
Operators: Same as C/C++ plus some others:
typeof(obj or type) (representation as Type), is (tests a type), as (cast or null)
Statements:
assignment;
expression;
if (bool_exp) { … } [ else { … } ]
switch (expr) switch_block
while (bool_expr) { … }
do { … } while (bool_expr);
for (init; cond; iter) { … }
foreach (var in expr) { … }
break;
continue;
throw [ expr ];
return [ expr ];
try { … } catch [ ( exception ) ] { … } finally { … }
lock (obj) { … }
using ( res_expr ) { … }
Some aspects of the C# Language 6
C# Classes❖Each class can have:
▪ Fields and Constants (const and readonly)
▪ Methods + constructors (instance and type)
▪ Finalizers
▪ Properties and indexers
▪ Events
▪ Operators and converters
▪ Nested types
❖Other class characteristics
▪ Simple inheritance (but multiple interfaces)
▪ Values can be treated as objects
▪ Much more …
Some aspects of the C# Language 7
Example C# - Value as an object
} “Boxing”
} “Unboxing”
object o = i;
int j = (int) o;
o System.Int32
123
j
?
123
int i = 123;
123i
Some aspects of the C# Language 8
Boxing and unboxing
struct Point {
public int x, y;
}
class App {
static void Main( ) {
ArrayList a = new ArrayList( );
Point p;
for (int k = 0; k < 10; k++) {
p.x = p.y = 1;
a.Add(p);
}
…
Point p1 = (Point) a[4];
}
}
public virtual void Add(object o);
automatic boxing
explicit unboxing
class App {
static void Main( ) {
Point p;
p.x = 10; p.y = 20 ;
Console.WriteLine(p.ToString());
Console.WriteLine(p.GetType());
Point p2 = (Point) p.Clone();
ICloneable c = p2;
object o = c.Clone();
p = (Point) o;
}
}
Another example
Some aspects of the C# Language 9
C# Modifiers
Accessibility for types, fields and methods
private (default for methods, fields)
protected
internal (default for non-nested)
protected internal (or)
public
(protected and internal) (not supported in C#)
Type attributes
abstract
sealed
Field attributes
(none) - instance
static
const
readonly
Method attributes
(none) - instance
static
virtual
new
override
abstract
Finalizers
Some aspects of the C# Language 10
Execute before the destruction of objects by the garbage collector
It is a non deterministic execution
Don’t have any modifiers
class Test {
. . .
~Test( ) {
// … finalization work
// … automatically calls the base class
// finalizer
}
}
Properties
Some aspects of the C# Language 11
Smart Fields (methods used with a field syntax)
class Data {
FileStream s;
public string FileName {
set {
s = new FileStream(value, FileMode.Create);
}
get {
return s.Name;
}
}
Usage:Data d = new Data();
d.FileName = “myFile.txt”;
string name = d.FileName;
For a property that is simply a getter and/or a setter of a private field we don’t need to
write the code:public int SomeValue { get; set; }
Indexers
Some aspects of the C# Language 12
methods that are used as an array element syntax
class File {
FileStream s;
. . .
public int this [int index] {
get { s.Seek(index, SeekOrigin.Begin);
return s.ReadByte();
}
set { s.Seek(index, SeekOrigin.Begin);
s.WriteByte( (byte)value );
}
}
Usage:
File f = . . .
int x = f[10];
f[11] = (int) ‘A’; It’s possible to define several indexers
with different index types
Nested types
Some aspects of the C# Language 13
It’s possible to define types inside types (usually classes)
class A {
int x;
B b = new B(this);
public void f() { b.f(); }
public class B{
A a;
public B(A a) { this.a = a; }
public void f() { a.x= ...; ... a.f(); }
}
}
class C {
. . .
A a = new A();
A.B b = new A.B(a);
. . .
}
Internal classes can access any member
from the external one (even private)
External classes can only access public
members of the internal classes
Other classes can access the internal classes
only if they are public
Structures, enumerations, interfaces and
delegates can also be nested
Generics
Some aspects of the C# Language 14
Type parameters applied to classes, interfaces, methods,
events or delegates
public class MyStack<T> {
T[] items = null;
int top = 0;
public MyStack(int capacity) {
items = new T[capacity];
}
public void Push(T item) { … }
public T Pop() { … }
}
…
MyStack<double> aStack = new MyStack<double>(100);
…
Delegates (1)
Some aspects of the C# Language 15
A delegate is a type representing a method (a smart, verifiable, method pointer type)
They can be instantiated with any method corresponding to the declared signature
When invoked executes the method used to instantiate it
Declaration: delegate void Notifier( string sender );
Equal to the declaration of a
method, but adding the delegate
keywordVariable: Notifier greetings;
Instantiation: void SayHello(string sender) {
Console.WriteLine("Hello from " + sender);
}
greetings = new Notifier(SayHello); or
greetings = SayHello;
Usage: greetings(“Mike”); // invokes SayHello(“Mike”)
Delegates (2)
Some aspects of the C# Language 16
The delegates are multicast: this means that they can contain several methods
(they must have all the same signature)
In this case, when invoked, they execute all the included methods
Notifier greetings;
greetings = SayHello;
greetings += SayGoodBye;
greetings("John"); // "Hello from John“
// "Good bye from John“
greetings -= SayHello;
greetings(“Mike"); // "Good bye from Mike"
When a delegate returns a value and is multicast, only the value from the last call
is returned (the same for out parameters)
Anonymous Methods
Some aspects of the C# Language 17
When needing or instantiating a delegate we can use anonymous methods:
Some examples:
delegate void SomeDel(int x);
SomeDel aDel = delegate(int k) { … k … }
void CreateAThread() {
Thread t1 = new Thread(delegate() { … });
t1.Start();
}
button1.Click += delegate(object sender, EventArgs e) {
MessageBox.Show(“Button pressed!”);
}
// explicit delegate initialization
// delegate method parameter
// event handler
Lambdas
Some aspects of the C# Language 18
Simple forms to express anonymous methods used to instantiate delegates
(input parameters) => expression
(x, y) => x == y
(int x, string s) => s.Length > x
() => SomeMethod()
x => x * x
(input parameters) => { statements }
n => { string s = n + " " + "World";
Console.WriteLine(s);
}
Lambdas can be asynchronous if declared so
async (input parameters) => { statements }
Events (1)
Some aspects of the C# Language 19
An event is a member (variable) belonging to a special delegate type (keyword event)
Can be subscribed by other classes
Only the class that declares the event can fire it (invoke)
class Model {
public event Notifier notifyViews;
public void Change() { ... notifyViews("Model"); } // fire the event
}
class View {
public View(Model m) { m.notifyViews += Update; } // subscribe the event
void Update(string sender) { Console.WriteLine(sender + " was changed"); }
}
class Test {
static void Main() { Model m = new Model();
new View(m);
m.Change(); }
}
Some aspects of the C# Language 20
Events (2)delegate void handler( );
public class event_gen {
…
public event handler ev;
void method( ) {
if ( … )
if (ev != null)
ev( ); // fire the event
…
}
}
public class use_event {
use_event( ) {
event_gen evg = new event_gen( );
evg.ev += new handler(ev_hdlr); // register a listener
…
}
void ev_hdlr( ) {
…
}
}
Asynchronous Calls (1)
Some aspects of the C# Language 21
• The CLR allows that any method from any class or struct (including remote
ones) could be invoked asynchronously. A new thread is automatically
created to execute the call.
Caller
callCallee
Synchronous Call
Caller
async callCallee
return result
wait for
result
caller and callee
run in parallel
Synchronous
call
Asynchronous
call
Some aspects of the C# Language 22
Asynchronous Calls (2)• Classical code in C# (using a delegate)
• We only need to create a delegate instantiated with the method to call, and
invoke the BeginInvoke( ) method from the delegate instance
delegate … name ( … );
name del = new name ( f );
IAsyncResult ar = del.BeginInvoke( params, … );
…
…
…
…
…
v = del.EndInvoke(ar);
ar.IsCompleted
AsyncCallback cb = new AsyncCallback(Handler)
void Handler(IAsyncResult ar) {
…
v = del.EndInvoke(ar);
…
}
Demo
Sieve
• EndInvoke() collects the call result
Some aspects of the C# Language 23
• A recent version of C# (5.0) introduced the keywords async and await
• Can be used with the Task .NET class
• async marks methods that have asynchronous calls inside them
• await make an immediate return, and continues execution after
the call completes
• the call can be a Task.Run or other async method
async void MethodAsync(int par) {
… // preparation
int res = await Task.Run<int>( () => MyTask(par) );
… // do something with res - completion
}
int MyTask(int par) {
… // some code
}
…
MethodAsync(1000);
…
Asynchronous Calls (3)
async methods can
return: void, Task or
Task<T>
Task has the property
IsCompleted to test in
the caller if the async
method has already
executed to completion
Task<T> has the property
Result. Getting it waits
for completion.
Keywords async and await
Some aspects of the C# Language 24
async void FooAsync() {
...
Task<int> task = CalcAsync();
...
...
int result = await task;
...
...
}
• If a method contains await it must be marked as async
and should have the suffix Async
• task and section run in parallel
• meaning of await:
- if task ready => get its result and continue with
- if not ready => return to caller and continue there;
execute ("continuation") when task gets readyTask<int> CalcAsync() {
return Task.Run(() => {...});
}Caller
FooAsync();FooAsync()
task = CalcAsync();CalcAsync()
result = await task;
"continuation"
threads marked
by different
colorsCaller
FooAsync();FooAsync()
task = CalcAsync();CalcAsync()
result = await task;
Some aspects of the C# Language 25
Accessing native code
• Invoking native code from native dynamic libraries (DLL’s) is very simple.
The native functions run in the same application domain that calls them.
• We need only to declare the functions using the static extern modifiers,
inside some class or struct
class something {
…
…
[DllImport(“some.dll”)]
static extern
int some_func(char ch, double d);
…
…
void method( ) {
…
v = some_func(‘b’, 14.21);
…
}
}
Simple types are transformed
correctly by default.
For more complex types
we can use some .NET
attributes to guide their
transformation and memory
layout (for instance in structs)
Some aspects of the C# Language 26
Framework Class Library (FCL)System
Int32,
String, …
Data WindowsWeb XML
Connection,
DataSet, …
UI Services
Runtime
Forms XmlDocument, …
…
EnterpriseServices
ServicedComponent, …
… …
Remoting
…
FCL evolution
• Organized in nested namespaces
• System is the base