380 likes | 485 Views
C# and Types. A chic type, a rough type, an odd type - but never a stereotype Jean-Michel Jarre. Review & Context. Types are defined by CLR, hence it is same across languages Two phases of .Net learning Basics – CLR, types, Language syntax VB.Net or C#
E N D
C# and Types • A chic type, a rough type, an odd type - but never a stereotype • Jean-Michel Jarre More Types & C#
Review & Context • Types are defined by CLR, hence it is same across languages • Two phases of .Net learning • Basics – CLR, types, Language syntax VB.Net or C# • Application – ADO.Net, ASP.Net, Windows Forms. More Types & C#
C# • C# aims to combine the high productivity of Visual Basic and the raw power of C++ • Microsoft outsiders claim – “C# as Microsoft's alternative to Java” • Although .Net supports all languages equally – c#, vb.net, jscript.net etc. Many companies like to pick one. • VB.Net and C# syntax comparisonhttp://www.visualbasicexpert.com/vbvscsharp.htm More Types & C#
Basics • CaSe SeNSitiVE • Comments//, /* */ or /// • /// use used for code documentation • Identifiers: • Don’t use underscores, abbreviations • Follow guidelines:Camel case for variablesPascal case for Class names, methods, properties and namespaces EmployeeName employee_name localVariable XMLReader XmlReader More Types & C#
Operators More Types & C#
Blocks • Variable scope is limited to blocks • Blocks are delimited by braces • In the example below s each block refers to a different variable. { string s; } { string s; } More Types & C#
Control flow • if statement – similar to c, c++ or java • Note the parenthesis after ‘if’ • Do we need a braces for if?Answer: Only for compound statements if (i>0) string s = “greater”else string s = “smaller” if ( boolean-expression ) embedded-statement else embedded-statement More Types & C#
Control Flow (contd.) • Switch statement – similar to c, c++ and java • Can switch on a string • Watch out for fall-through void Func(string option) { switch (option) { case "label": goto case "jump": case "jump": goto default; default: break; } } More Types & C#
Control Flow • while and for - similar to c, c++ and java • foreach – new construct, used for collections, arrays. ArrayList numbers = new ArrayList(); ... // fill numbers with 0 through 9 ... foreach (int number in numbers) { Console.Write("{0} ", number); } More Types & C#
More Value Types • Recall value types are allocated on stack • struct – user defined value type • How are structures different from classes?Answer: since they live on stack they are fast, highly efficient. Hence, use structs only when you need performance struct Point { public int X, Y; }; More Types & C#
Reference Types More Types & C#
String Type • string is an alias for System.String • Immutable – just as in java • They are allocated on the heapDraw memory model picture for string s = “hello”; • They are NOT array of characters. • StringBuilder • Represents a mutable character string • Used when a strings need to be modified repeatedly. More Types & C#
String Type (contd.) • Literals, two ways: • Quoted • @ Syntax //Quoted string s = “hello”; // 2 backslashes to avoid escape sequence string path = “c:\\temp”; //@Syntax string path = @”c:\temp”; More Types & C#
String Type (contd.) • Operators • Equality (==), concatenation (+=), indexer [ ] are overloaded • Equality (==) operator works differently in java. string s = “hello”; if (s == “hi”) // equality, comparison .. s += “ world” // concatenation char c = s[1]; // array type access More Types & C#
Class Type • User defined reference type • Notice the naming conventions class Employee { private string name; private decimal salary; public decimal SalaryCap = 10000.00M; //default access is private string secretary; } More Types & C#
Constructor • Compiler declares a default c'tor • You can declare the default c'tor • If you declare a c'tor the compiler doesn't class Employee { private string name; private decimal salary; public Employee(string n, decimal d) { name = n; salary = d; } public Employee(string n) // call other c’tor :this(n, 0.0M) { } } More Types & C#
Fields • Instance fields • they belong to the object instance • one per object. E.g.. Name, Salary in Employee class. • Readonly fields – use keyword readonly • Should be initialized at declaration time or in c’tor. • Static fields – use keyword static • They belong to the class type • Access only via class name • Const fields - use keyword const • are implicitly static • only simple types, enums, & string can be const • const fields require a variable initializer More Types & C#
Fields (Contd.) • Employee Class class Employee { //instance fields private string name; private decimal salary; public readonly decimal SalaryCap = 10000.00M; public const int StartEmpNum = 1000; } More Types & C#
Object Creation • Use new keyword • Call constructor • Draw memory map for the following: class Employee { //instance fields private string name; ... // Entry point public static void Main() { Employee e1 = new Employee(“John"); Employee e2 = new Employee("Mary", 11000); Employee e3 = new Employee(); //Error ??? } } More Types & C#
Passing parameters • By copy • Default • No special keyword • By reference • ref keyword • Out parameter • out keyword • Gives write access More Types & C#
Arrays • Arrays are reference types, they allocated on the heap // Array declaration int[] myArray = null; int[,] myArray2; // 2 dimensional Employee[] staff; // Array allocation int[] myArray = new int[4]; int[,] myArray2 = new int[2,3]; //declaration, allocation and initialization int[] myArray = new int[4] {1,2,3,4}; int[] myArray = {1,2,3,4} //shortcut More Types & C#
System.Array • All arrays are derived from System.Array type • It has some important properties: • Length, number of elements • Rank, number of dimensions • Important methods: • Copy • Sort • Clear • BinarySearch More Types & C#
params keyword • C# allows variable number of parameters for a method public void PrintMe(params int[] val) { … } public void Main() { PrintMe(1); PrintMe(2, 3); PrintMe(3, 5, 5); } More Types & C#
Inheritance • A class can inherit from a single base class • By default methods are not virtual • struct cannot inherit from a struct or class • There is no extends keyword as in java public class Vehicle { … } public class Car:Vehicle {… } More Types & C#
Inheritance From a base class perspective • virtual method • Method may be replaced by derived class • abstract method • Method must be replaced a derived class • sealed method • A method may not be replaced by a derived class • override method • Method replace a method in the parent (base) class. It is still overridable by further derived classes. • new method • Method is unrelated to a similarly defined method in the parent class. Used when there is a change made to the base class resulting in name clash in the child class. From a derived class perspective More Types & C#
Inheritance • A class can call its parent constructor using base keyword class Manager:Employee { public Manager(string n) :base(n) {} } More Types & C#
Inheritance Example public class Employee{ public static void Main(){ Employee e = new Employee(); e.RaiseSalary(5); //calls employees raise method Manager m = new Manager(); m.RaiseSalary(5);//calls manager method m.GenerateID(); //calls employees method } // may be overridden public virtual void RaiseSalary(double percent){ } // statically bound cannot be overridden public void GenerateID() { } } public class Manager: Employee { // specialized method for Manager only public override void RaiseSalary(double percent){ } } More Types & C#
Abstract Class • A class that cannot be instantiated • It is useful when you derive from it abstract class Vehicle { } class Car: Vehicle { } ... { Vehicle v = new Vehicle(); // error Car c = new Car(); //Ok } More Types & C#
Interface • Interface contains method signature only • It serves like a contract interface IBoardMember { public int StockOptions(); // no implementation } //Executive is agreeing to the “contract” in IBoardMember class Executive: Manager, IBoardMember { //class executive has to implement StockOptions public int StockOptions() {... } } More Types & C#
Interfaces • Popular Interfaces • ICloneable • IDisposable // achieves object copying (deep copy) class ICloneable { public Object Clone(); } // achieves object cleanup class IDisposable { public void Dispose(); } More Types & C#
Object • Everything is derived from System.Object • object is alias for System.Object • Even value types- structs, enums, int32 • Does this pose a overhead? • inheritance always has extra processing? • Answer: The framework uses special techniques, value types (int32 etc.) do not directly inherit from object • Exercise: • Check what methods are available on System.Object More Types & C#
Down Casting • A reference to base type can refer to any of its derived types • Other way is not allowed • Hence, a reference to object type can refer to any object { Employee e; Manager m = new Manager(); e = m; //allowed, down casting Employee e2 = new Employee(); m = e2; // not allowed } More Types & C#
Exception Handling • Exception is a class that represent errors during application execution. • All Exceptions inherit from System.Exception • This replaces arcane error codes used in legacy systems • Exercise: • List 5 exceptions derived from System.Exception in the .Net framework More Types & C#
try-catch syntax try { // try to read a text file StreamReader sr = new StreamReader("TestFile.txt"); string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } // if error come here // ex contains all the info about error catch (IOException ex) { Console.WriteLine(ex.StackTrace); } // finally is always executed finally { sr.Close(); } More Types & C#
Delegates • A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature • A delegate lets you pass a function as a parameter • Just like in declaration “string s;” s can point to any string, “MyDelegate” can point to any method which takes a integer parameter. // delegate declaration delegate void MyDelegate(int i); More Types & C#
Delegate // delegate declaration delegate void MyDelegate(int i); class Program{ public static void Main(){ TakesADelegate(new MyDelegate(DelegateFunction)); } public static void TakesADelegate(MyDelegate SomeFunction) { SomeFunction(21); } public static void DelegateFunction(int i) { System.Console.WriteLine("Called by delegate with number: {0}.", i); } } More Types & C#
Events • A delegate field can be marked as an event • Widely used in GUI classes • only += and -= can be performed on the field More Types & C#
Attributes • Attributes allow code elements to be tagged with declarative information • They are can queried using reflection [DeveloperName(“John B”)] public class MyClass { … } More Types & C#