Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
C# .NET C# language C# • • • • A modern, general-purpose object-oriented language Part of the .NET family of languages ECMA standard Based on C and C++ .NET • Multiple languages which can interoperate • Languages compile to a common intermediate language • Common Language Runtime runs programs from all the .NET languages C# versus Java • Both intended to be improvements on C and C++ – Java aims to be one language for many platforms • portable (platform-independent) • safe – C# aims to provide many languages for a single platform • power • unsafe code is allowed • not platform-independent Language Features • • • • • • Strong type checking Array bounds checking Detection of uninitialized variables Automatic garbage collection Designed for use in distributed environments Supports internationalization First Program namespace FirstProgram { class First { static void Main() { System.Console.WriteLine( "Welcome to C#!"); } } } C# on onyx • Workstations have a Windows virtual machine with C# Express installed • See the handout at http://cs.boisestate.edu/~tcole/cs354/fall11/handouts /csharp.pdf • There is also a version of mono, an opensource implementation of C# – Command is monodevelop C# Express • VMWare should get installed on all the workstations in the lab – Not on the server – Virtual machine is frozen • you have to transfer any files you create onto onyx – Use SSH Secure File Copy program Getting your own copy • C# Express – Free from Microsoft – http://www.microsoft.com/visualstudio/enus/products/2010-editions/visual-csharp-express – .NET Development Environment • Available to you through MSDN Alliance Keywords (reserved) abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual volatile void while Keyword correspondence • base - used like this for accessing overridden methods from parent class •const - used for constants instead of final • foreach - like for : in java • namespace - serves similar purpose to import •sealed - similar to final for overridden methods and derived classes New Keywords • checked - causes OverflowException for integer overflow instead of silent overflow • override - used to label overridden methods • virtual - allows a method to be overridden • uint, ulong, ushort - unsigned integer types • decimal - fixed-point type • partial - a type definition or a method definition can be spread over more than one file • ref, out - modifiers for method parameters C# Program Structure • A program consists of one or more files • A file can contain one or more classes and/or namespaces – name of file is not tied to name of class • At least one class must contain Main – There are several allowed signatures • return type is either int or void • either no parameter or String array C# Types • Unified type system – Everything can be treated as an object • Value types – simple types: primitive types from Java plus unsigned types and decimal – structs – enum • Reference types - like object references in Java • Pointer types - used only in unsafe code Operators • Java operators with similar precedence • Extra operators – – – – typeof - returns class name (getClass()) checked/unchecked (overflow) is (like instance of) as (returns cast value or null) • Unsafe operators – *, &, sizeof Operators: differences from Java • C# allows you to overload operators • == compares values for strings and simple types, addresses for all other objects Console I/O • System.Console.WriteLine( arg) – argument can be any type – for objects, ToString is invoked • System.Console.ReadLine() – returns a String • System is a namespace – using System; allows you to omit the namespace when calling the method Namespaces • Sort of like a package – in Java, package statement applies to everything in the file – can import all or part of a package • A single C# file can contain classes from different namespaces – using imports entire namespace C# Class Members • Data Members – Field • instance • static – – – – Constant Read-only Delegate Event • Function Members – – – – – – – – Instance constructor Static constructor Method Property (accessor/mutator) Indexer Operator Destructor (finalizer) Nested types (inner classes) C# Class Modifiers • new • abstract • sealed (final) • access modifiers – – – – public protected internal private Inheritance • Single inheritance (System.Object) class <class_name>:<super_class> {… } • Interfaces provide restricted form of multiple inheritance interface <interface_name> {… } – Syntax for implementing is same as for inheritance – Multiple interfaces separated by comma – Super class, if any, must be first in list Methods • Same syntax as Java • Default access is private (rather than package) • Value types are passed by value usually – ref keyword used to pass by reference – out keyword provides for return values • Reference types behave as in Java Properties • C# properties provide the same service as Java's accessors and mutators public string Color { String MyColor; get {return MyColor;} set { MyColor = value; } } • Use the name Color to get value of or assign value to private instance variable MyColor Object Initializers public class Bunny { public string Name; public bool LikesCarrots; public bool LikesHumans; public Bunny () {} public Bunny (string n) { Name = n; } } Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false }; Bunny b2 = new Bunny ("Bo") { LikesCarrots=true, LikesHumans=false }; Control Statements • do, while, for, if-else same as in Java • foreach provides loop for arrays • switch-case like Java except – string case values are allowed – no fall-through behavior • use goto case <label> instead • C# has goto statement String • string is alias for System.String • reference type – equality operators use value semantics • Literals are written with double quotes around them – use \ for escape character • Verbatim string preceded by @ – escape character not supported – can span multiple lines string verbatim = @" verbatim string with a "" in it" Arrays • Arrays are objects – Subclasses of System.Array – Reverse, Sort, IndexOf methods • Declaration, instantiation, initialization, element access as in Java for 1D arrays int []MyArray = new int[5]; – Length property gives the number of elements – Only this syntax is allowed Arrays • For rectangular 2D arrays int [,] Array2D = new int[2,5]; – Length property gives total number of elements – Element access is the same as in Java • For jagged arrays int [][] JaggedArray2D = new int[2][]; JaggedArray[0] = new int[3]; Structs • A struct is very similar to a class except – structs are value types; classes are reference types – no inheritance – struct has a default constructor always – all constructors must initialize all data – can be "instantiated” without new Exceptions • System.Exception • try-catch-finally has same syntax as Java – Don't need a variable name in catch if you aren't going to use it – Within catch block, throw throws the exception that was caught • All exceptions are unchecked Delegates • Delegate is a special type that encapsulates one or more methods public delegate int MyDelegate( string s, int i); • Instantiate with a method that has the same signature and return type MyDelegate d2 =new MyDelegate(obj.ObjectMethod); Events • C# event model is similar to Java - delegation based • An Event is a special type of Delegate • Event is created by event source when an event occurs. The Event is passed to the event consumer's handler • Handlers must be registered with the event source etc. • Operator overloading • Reflection - asking a class for information about itself • Attributes – Used to add annotation to a class that can be read using reflection • Preprocessor • Unsafe code mono • mono is an open-source project that provides facilities for running C# programs under Linux http://www.mono-project.com • Compile a program by typing mcs First.cs • Run a program by typing mono First.exe Reference Material • Safari books at Albertson's Library – C# in Depth – Learning C# – Microsoft Visual C# Step by Step – Programming C#