Brief Introduction To C# The Native Language Of

2y ago
36 Views
2 Downloads
320.44 KB
13 Pages
Last View : 13d ago
Last Download : 3m ago
Upload by : Audrey Hope
Transcription

COMPSCI 711C# 1.2radu/2009Brief introduction to C# – the native language of .NETo C# Language Specifications, 4th Edition, Standard ECMA-334, 2006, Ch 8 – Language ions/standards/Ecma-334.htmo CSharp Language Specification, Version 3.0, 2007, Ch 1 – p/aa336809.aspxCompiling from the command-lineo We need csc on the patho We can also call vsvars32.batAssembly .NET executable binary: .EXE or .DLLEx: mscorlib.dll, System.Windows.Forms.dllSET PATH llCompilers (csc) and Tools (VS) aretypically configured to automaticallyreference several ―core‖ libraries, suchas mscorlib.dllhello.csLinqPadA great 3rd party free interactivetesting tool1.13

COMPSCI 711C# 1.2radu/2009Type system unificationAll types—including value types—derive from the root type object (in one or more steps)7.ToString();// Value types and reference typesThe different meanings of B AReference type : one balloon, two handles Value typeobjectboxingunboxingA: 7B: 7ABo An int value can be converted (actually copied) to an object (boxing)o and back again to int (unboxing).object o i;// implicit boxing, by copyint j (int) o;// explicit unboxing, by copyUsed carefully, boxing provides object-ness, without introducing unnecessary overhead (careful).2.13

COMPSCI 711C# 1.2radu/2009Boxing in Classic Collectionspublic class Stack {public void Push(object o){. }public object Pop(){. }}Stack stack new Stack();stack.Push(12);int i (int)stack.Pop();Safe type-castfor reference typesstring s s stack.Pop()stack.Pop()asasstring;string;o What if the top is not an int?o Exception! needs a try blocko or a safe typecasto s null if cast is not possibleo sNo nullif cast is not possibleexception!No exception!Generic Collectionspublic class Stack T {public void Push(T o){. }public T Pop(){. }}Stack int stack new Stack int ();stack.Push(12);int i stack.Pop(); // conversion not neededAdvantageso Static type safetyo PerformanceLater we’ll talk a bit more about generictypes and methods3.13

COMPSCI 711C# 1.2radu/2009Reference parameters – the values of corresponding variables may changestatic void Swap(ref int a, ref int b) {int t a;a b;pre:x 1, y 2b 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 unimportantstatic void Divide(int a, int b,out int quotient, out int remainder) {quotient a / b;remainder a % b;}int i 5, j 2, q, r ;Divide(i, j, out q, out r);Console.WriteLine("{0} / {1} {2} rest {3}",i, j, q, r);5 / 2 2 rest 14.13

COMPSCI 711C# 1.2radu/2009A 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 belowF( );F(1);F(1, 2);F(1, 2, 3);F(new int[] {1, 2, 3, 4});foreach statementso foreach can be applied to any array, collection, or stringo in fact to any object that implements IEnumerable or IEnumerable T – i.e., to sequenceso foreach statements make life easier for users such sequenceso we’ll see later how iterators simplify the task of sequence developersint[] 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);}5.13

COMPSCI 711C# 1.2radu/2009PropertiesProperties extend fields. However, instead of defining storage locations, properties have get andset accessors that specify the statements to be executed when their values are read or written.public class Button { // simplifiedprivate string caption;public string Caption {get {return caption;}set {caption value;Repaint();}}}Button b new Button();b.Caption "ABC";// set; causes repaintstring s b.Caption;// getb.Caption "DEF";// get & set; causes repaintthe same in old Java-like styleb.setCaption( b.getCaption() ―DEF‖ );which one is more readable?6.13

COMPSCI 711C# 1.2radu/2009Indexers – look like associative arraysAn indexer is a property extended with parameters, that enables an object to be indexed like an array– and its ―indices‖ can be not only integers, but also strings or any other object type.// Sample usage:public class Vector { // simplifiedVector v new Vector();public object this[int index] {v[0] 10;// setget {// setif (! ValidIndex(index)) throw v[1] 11;int i v[1];// getelse return some value v[1] 2;// get & set}// Traditional usageset {v.set ElementAt(2, v.get ElementAt(2); 2);if (! ValidIndex(index)) throw else store some value }A collection example: Dictionary TKey, TValue generic class}Maps key objects, typically strings object values.Indexers can be overloaded, e.g.,}Dictionary string, string openWith new Dictionary string, string ();public object this[string index] { }openWith["rtf"] "winword.exe";7.13

COMPSCI 711C# 1.2radu/2009Struct’s (structures)Similar to classes but more ―light-weight‖:o struct’s are value types rather than reference typeso inheritance is not supported for struct’so 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 the last values of p and qo what will happen if Point were a class8.13

COMPSCI 711C# 1.2radu/2009Delegateso Delegates are object-oriented, type-safe, and secure function pointers that encapsulates one ormore methods (multicast), together with their associated instance or class.{ (instance, method on that instance), (class, method on that class), }.delegate void SimpleDelegate();// matches both S and I belowclass Test {public static void S() { }public void I() { }}As we will see later, methodscan also be defined on-the-fly,via anonymous delegates orlambda expressions.SimpleDelegate d;d new SimpleDelegate(Test.S);d Test.S;d();// or// since C# 2.0// calls Test.S()// SimpleDelegate d;Test t new Test();d t.I;d();// calls t.I()// SimpleDelegate d;d Test.S; d t.I;d();// calls Test.S() and t.I()9.13

COMPSCI 711C# 1.2radu/2009Eventso 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 definitionpublic class Button { // simplifiedpublic event EventHandler Click;public void Reset() {Click null;}// somewhere we fire the event// and this will broadcast it// to all registered handlers, if anyif (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 (1)!");}void Button1 Click2(object sender, EventArgs e) {Console.WriteLine("Button1 was clicked (2)!");}What is executed? Considerpublic void Disconnect() { several scenarios.Button1.Click - Button1 Click2;}}10.13

COMPSCI 711C# 1.2radu/2009Attributeso To attach declarative information to various program entities, such as methods, fields and classes,and later retrieve and interpret 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: OperationContract Attribute (WCF, more later)System definition:public sealed class OperationContractAttribute : AttributeSample usage:[OperationContract()] AddToCart(object o) { }[OperationContract] AddToCart(object o) { }[OperationContract(IsOneWay true)] AddToCart(object o){ }Other examplesStructLayout To create union types (unavailable in the language)DllImportTo import ―legacy‖ DLLsObsoleteCompiler will complain if target is used11.13o Attribute usage is really objectinstantiation.o A crisp notation combiningconstructor call plus propertysetup, e.g.,OperationContractAttribute oc new OperationContractAttribute ();OperationContractAttribute oc new OperationContractAttribute ();oc.IsOneWay true;

COMPSCI 711Versioning, explicitvirtual chains,broken chainsC# 1.2radu/2009Solves the ―fragile base class‖ 336813.aspxhttp://www.cs.aau.dk/ e-fbc-problem.htmlclass 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 newExplicit overriding!Explicit virtual chain A-B-C.12.13Partial overriding!―Broken chain‖ between B and C(2 chains: A-B and C)

COMPSCI 711C# 1.2radu/2009Summary of the possibly most interesting new language features (C# version 1)Type system unification & boxing7.ToString(); stack.Push(12);Type-safe castingobj as PointRef/out parametersSwap(ref int a, ref int b)Params arraysF(1); F(1, 2); F(1, 2, 3);Foreach loopsforeach (string s in args) { }Propertiesint MyProp {get {return ;} set { }}Indexersint this[int index] {get {return ;} set { }}Structuresstruct Point {public int x, y;}Delegatesdelegate void SimpleDelegate();EventsButton1.Click Button1 Click1; //new EventHandler( )Attributes[OperationContract(IsOneWay true)]public bool AddToCart(object o)Versioning – explicit overridepublic virtual void f() { }public override void f() { }13.13

COMPSCI 711 C# 1.2 radu/2009 2.13 boxing o An int value can be converted (actually copied) to an object (boxing) o and back again to int (unboxing). object o i; // implicit boxing, by copy int j (int) o; // explicit unboxing, by copy Used carefully, boxing provides object-ness, without introducin

Related Documents:

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

Chính Văn.- Còn đức Thế tôn thì tuệ giác cực kỳ trong sạch 8: hiện hành bất nhị 9, đạt đến vô tướng 10, đứng vào chỗ đứng của các đức Thế tôn 11, thể hiện tính bình đẳng của các Ngài, đến chỗ không còn chướng ngại 12, giáo pháp không thể khuynh đảo, tâm thức không bị cản trở, cái được

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. Crawford M., Marsh D. The driving force : food in human evolution and the future.

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. 3 Crawford M., Marsh D. The driving force : food in human evolution and the future.