Anda di halaman 1dari 12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Introduction to C# the native language of .NET


o C# Language Specifications, 4th Edition, Standard ECMA-334, 2005, Chapter 8
http://www.ecma-international.org/publications/standards/Ecma-334.htm
Compiling from the command-line
Assembly = .NET executable binary: .EXE or .DLL
need csc on the path sdkvars.bat
Ex: mscorlib.dll, System.Windows.Forms.dll
call \sdkvars.bat
csc hello.cs
csc /target:exe /out:hello.exe /r:mscorlib.dll hello.cs
The different meanings of B = A
Reference type : one balloon, two handles

Value type

object

boxing
A: 7

B: 7

1.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Type system unification


All typesincluding value typesderive from the type object
7.ToString();

//

An int value can be converted to object (aka boxing) and back again to int (aka unboxing).
object o = i;
int j = (int) o;

// boxing
// unboxing

Used carefully, boxing provides object-ness, without introducing unnecessary overhead (hmm).
public class Stack {
public void Push(object o) {
... }
public object Pop(){
... }
}

Stack stack = new Stack();


stack.Push(12); //automatic boxing
int i = (int)stack.Pop();
// explicit unboxing
o What if the top is not an int?
=> Exception! needs try
or safe typecast
2.12

safe type-cast
string s = stack.Pop() as string;
o s = null if cast not possible
No exception!

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Reference parameters the values of corresponding variables may change

static void Swap(ref int a, ref int b) {


int t = a;
a = b;
pre: x = 1, y = 2
b = t;
post: x = 2, y = 1
}

int x = 1; int y = 2;
Console.WriteLine("pre: x = {0}, y = {1}", x, y);
Swap(ref x, ref y);
Console.WriteLine("post: x = {0}, y = {1}", x, y);

An output parameter - like a ref parameter, but the initial value is unimportant
static void Divide(int a, int b,
out int result, out int remainder) {
result = a / b;
remainder = a % b;
}

int i = 5, j = 2, ans, r ;
Divide(i, j, out ans, out r);
Console.WriteLine("{0} / {1} = {2} rest {3}",
i, j, ans, r);
5 / 2 = 2 rest 1

3.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

A parameter array represents a variable length argument list.


static void F(params int[] args) {
Console.WriteLine("# of arguments: {0}", args.Length);
for (int i = 0; i < args.Length; i++)
Console.WriteLine("\targs[{0}] = {1}", i, args[i]);
}
// could also use foreach, as below

F( );
F(1);
F(1, 2);
F(1, 2, 3);
F(new int[] {1, 2, 3, 4});

foreach statements
o foreach can be applied to any array, collection, or string
o in fact to any object that implements IEnumerable
int[] args = ;
ArrayList args = ;
foreach (int a in args) {
Console.WriteLine(a);
}

IEnumerator myEnumerator = args.GetEnumerator();


while (myEnumerator.MoveNext()) {
int a = (int) myEnumerator.Current;
Console.WriteLine(a);
}

4.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Properties
Properties are a natural extension of fields. However, unlike fields, properties do not denote
storage locations. Instead, properties have accessors that specify the statements to be executed
when their values are read or written.
public class Button {
private string caption;
public string Caption {
get {
return caption;
}
set {
caption = value;
Repaint();
}
}
}

Button b = new Button();


b.Caption = "ABC";
// set; causes repaint
string s = b.Caption;
// get
b.Caption += "DEF";

// get & set; causes repaint

the same in old Java-like style


b.setCaption( b.getCaption() + DEF );
which one is more readable?

5.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Indexers
An indexer is a sort of property-like member with parameters, that enables an object to be indexed in
the same way as an array and its indices can be of any object type, e.g., integers, strings, etc.
public class Vector {

public object this[int index] {


get {
if (! ValidIndex(index)) throw
else return some value
}
set {
if (! ValidIndex(index)) throw
else store some value
}
Indexers can be overloaded, e.g.,
}
public object this[string index] {}
}

// Sample usage:
Vector v = new Vector();
v.Add(10); v.Add(20); v.Add(30);
int i = v[0];
v[1] = 22;
v[2] += 3;

// get
// set
// get & set

// Traditional usage
int i = v.get_ElementAt(0);
v.set_ElementAt(1, 22);
v.set_ElementAt(2,
v.get_ElementAt(2); + 3);

6.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Structs (structures)
Similar to classes but more light-weight:
o structs are value types rather than reference types
o inheritance is not supported for structs
o struct values are stored on the stack or in-line
o struct values are copied on assignment (=)
o careful use may enhance performance.
struct Point {
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Point p, q;
p = new Point(10, 20);
q = p;
q.x = 30;
o check p and q
o what will happen if Point were a class

7.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Delegates
o Delegates are object-oriented, type-safe, and secure function pointers.
o A delegate instance encapsulates one or more methods (thus multicast is supported), each of
which is referred to as a callable entity.
o For instance methods, a callable entity = (an instance, and a method on that instance).
o For static methods, a callable entity = (a class, and a method on that class).
delegate void SimpleDelegate();
// matches both S and I below
class Test {
public static void S() {}
public void I() {}
}

SimpleDelegate d;
d = new SimpleDelegate(Test.S);
// or
d = Test.S;
// since C# 2.0
then
d();
// calls Test.S()
Test t = new Test();
d = t.I;
d();

// calls t.I()

d = null; d += Test.S; d += t.I;


d();

// calls Test.S() and t.I()

8.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Events
o An event is a member of a delegate type that enables an object or class to provide notifications.
o Only += and -= are available from outside (why?).
public delegate void EventHandler(
object sender,
System.EventArgs e);
// System definition
public class Button {
public event EventHandler Click;
public void Reset() {
Click = null;
}
// somewhere we fire the event
// and this will broadcast it
// to all registered handlers, if any

if (Click != null) Click(, );


}

public class Form1: Form {


Button Button1 = new Button();
public void Form1() {
Button1.Click += Button1_Click1;
Button1.Click += Button1_Click2;
}
void Button1_Click1(object sender, EventArgs e) {
Console.WriteLine("Button1 was clicked!");
}
void Button1_Click2(object sender, EventArgs e) {
Console.WriteLine("Button2 was clicked!");
}
What is executed? Consider
public void Disconnect() { several scenarios.
Button1.Click -= Button1_Click2;
}
}
9.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Attributes
o Through its support for attributes, C# allows programmers to invent new kinds of declarative
information, attach this declarative information to various program entities, such as methods, fields
and classes, and later retrieve this declarative information at run-time (using reflection)
o ASP.NET, XML and most run-time environments rely heavily on specific system-defined attributes.
Example: WebMethod Attribute
System definition:
public sealed class WebMethodAttribute : Attribute
Usage:
[WebMethodAttribute()] AddToCart(object o) {}
[WebMethod] AddToCart(object o) {}
[WebMethod(true)] AddToCart(object o) {}
[WebMethod(EnableSession=true)] AddToCart(object o) {}
Other examples
StructLayout To create union types (unavailable in the language)
DllImport
To import legacy DLLs
Obsolete
Compiler will complain if target is used
10.12

o Attribute usage is really object


instantiation.
o A crisp notation combining
constructor call plus property
setup, e.g.,
WebMethodAttribute wm =
new WebmetodAttribute();
WebMethodAttribute wm =
new WebmetodAttribute(true);
WebMethodAttribute wm =
new WebmetodAttribute();
wm.EnableSession=true;

Arhitecturi distribuite orientate pe servicii web

C# 1.2

Versioning, explicit virtual chains, broken chains

radu/2008

fragile base class problem

class A {
public void f() { }
}

class A {
public virtual void f() { }
}

class A {
public virtual void f() { }
}

class B: A {
public void f() { }
}

class B: A {
public override void f() { }
}

class B: A {
public override void f() { }
}

class C: B {
public void f() { }
}

class C: B {
public override void f() { }
}

class C: B {
public new virtual void f() { }
}

A x = new C();
x.f(); // A.f()

A x = new C();
x.f(); // C.f()

A x = new C();
x.f(); // B.f()

No implicit overriding!
Warning w/o new

Explicit overriding!
Chain A-B-C.

Partial overriding!
Broken chain between B and C
(2 chains: A-B and C)

11.12

Arhitecturi distribuite orientate pe servicii web

C# 1.2

radu/2008

Summary of the 12 new language features that are most interesting at this stage
Type system unification & boxing

7.ToString(); stack.Push(12);

As casting

obj as Point

Ref/out parameters

Swap(ref int a, ref int b)

Params arrays

F(1); F(1, 2); F(1, 2, 3);

Foreach loops

foreach (string s in args) { }

Properties

int MyProp {get {return ;} set { }}

Indexers

int this[int index] {get {return ;} set { }}

Structures

struct Point {public int x, y;}

Delegates

delegate void SimpleDelegate();

Events

Button1.Click+=Button1_Click1; //new EventHandler()

Attributes

[WebMethod(true)] public string GetX() {}

Versioning explicit override

public virtual void f() { }


public override void f() { }

12.12

Anda mungkin juga menyukai