520 likes | 789 Views
EEC-492/592 Kinect Application Development. Lecture 3 C# Primer Wenbing Zhao wenbing@ieee.org. Outline. C# primer Based on C# in a nutshell book: http://shop.oreilly.com/product/9780596001810.do C# Programming Guide http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx.
E N D
EEC-492/592Kinect Application Development Lecture 3 C# Primer Wenbing Zhao wenbing@ieee.org
Outline C# primer Based on C# in a nutshell book: http://shop.oreilly.com/product/9780596001810.do C# Programming Guide http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx
The C# Language Created in 2000 by Microsoft “C# is a simple, modern, object-oriented, and type-safe programming language derived from C and C++” C# bears many syntactic similarities to C++ and Java The .NET framework: consists of two elements CLR: common language runtime. Ensures managed execution of C# programs FCL: framework class library. A diverse array of higher-level software libraries (over 3,500 classes)
A First C# Program • This program writes “Hello world!” to the console window • Main() method: entry point of execution • Console class: standard input/output functionality, in System namespace namespace FirstProgram { using System; class Example { static void Main () { Console.WriteLine ("Hello world!"); } } }
Identifiers and Keywords • Identifiers are names we use to define types, methods, variables, etc. • C# identifiers are case-sensitive • C# keywords
Type Basics • A C# program consists of three basic elements • Functions: performs an action by execution a series of statements • Data: values that functions operate on • Types: a set of data members and function members • Most common types: classes and structs – template for creating data • Examples to follow: string, int, a custom type
The String Class • The string class specifies a sequence of characters • using System; • class Test { • static void Main () { • string s = ".NET"; • Console.WriteLine (s.ToLower()); // outputs ".net" • Console.WriteLine (s.Length); // outputs 4 • } • }
The intStruct • The int struct specifies a signed integer: 32 bit long • using System; • class Example { • static void Main () { • int a = 3; • int b = 4; • Console.WriteLine (a * b); • } • }
A Custom Type // Imports types from System namespace, such as Console using System; class Counter { // New types are typically classes or structs // --- Data members --- int value; // field of type int int scaleFactor; // field of type int // Constructor, used to initialize a type instance public Counter(int scaleFactor) { this.scaleFactor = scaleFactor; } // Method public void Inc() { value+=scaleFactor; } // Property public int Count { get {return value; } } }
A Custom Type class Test { // Execution begins here static void Main() { // Create an instance of counter type Counter c = new Counter(5); c.Inc(); c.Inc(); Console.WriteLine(c.Count); // prints "10"; // create another instance of counter type Counter d = new Counter(7); d.Inc(); Console.WriteLine(d.Count); // prints "7"; } }
Type Instances & Type Conversions • In general, we need to create instances of a type to use that type • Exception: static members of a type can be accessed without creating an instance • static void Main() • Conversions • int x = 123456; // int is a 4-byte integer • long y = x; // implicit conversion to 8-byte integer • short z =(short)x // explicit conversion to 2-byte integer
Reference Types • When an object of a reference type is created, the variable to which the object is assigned holds only a reference to that memory • When the object reference is assigned to a new variable, the new variable refers to the original object • Changes made through one variable are reflected in the other variable because they both refer to the same data
Value Types • When an instance of a value type is created, the variable to which the type is assigned holds the value type’s actual data • When one value type variable is assigned to a new variable, it is copied • The new variable and the original variable therefore contain two separate copies of the same data • Changes made to one copy do not affect the other copy 13
Value Types and Reference Types • Value types (struct, enum) • Directly contain data, e.g., int, bool • Assign one value to another: a copy is made • Predefined value types • Integer, signed (sbyte, short, int, long) • Integer, unsigned (byte, ushort, uint, ulong) • Floating-point (float, decimal, char, bool) • Reference types (class, array, delegate, interface) • An object and a reference to that object 14
Array: store a list of things type [*] array-name = [ new type [ dimension+ ][*]*; | { value1, value2, ... };] [*] is the set: [] [,] [, ,] ... Array size defined this way is static System.Collection provides dynamic arrays To use arrays Declaring arrays Initializing arrays Accessing array members Array
Types of Arrays • Single dimensional array • Declaring single dimensional array: int[] numbers; • Declaring does not create an array, to create one: • int[] numbers = new int[5]; • Multidimensional array • string[,] names; • string[,] names = new string[5,4]; • Jagged array (array of arrays) • byte[][] scores;
Jagged Arrays and More • Creating a jagged array: byte[][] scores = new byte[5][]; for (int x = 0; x < scores.Length; x++) { scores[x] = new byte[4]; } • mixed arrays • int[][,,][,] numbers;
Arrays: An Example App • // arrays.cs • using System; • class DeclareArraysSample { • public static void Main() { • int[] numbers = new int[5]; // Single-dimensional array • string[,] names = new string[5,4]; // Multidimensional array • byte[][] scores = new byte[5][]; // Array-of-arrays (jagged array) • // Create the jagged array • for (int i = 0; i < scores.Length; i++) { • scores[i] = new byte[i+3]; } • // Print length of each row • for (int i = 0; i < scores.Length; i++) { • Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length); } • } • }
Variable and Parameters • A variable represents a typed storage location • A variable can be a local variable, parameter, array element, an instance field, or a static field • All variables have an associated type • Defines the possible values the variable can have and the operations that can be performed on that variable • All variables must be assigned a value before they are used • A variable is either explicitly assigned a value or automatically assigned a default value. • Automatic assignment occurs for static fields, class instance fields, and array elements not explicitly assigned a value (default init value typically is 0 or null)
Variable and Parameters: Example using System; class Test { int v; // Constructors that initalize an instance of a Test public Test() {} // v will be automatically assigned to 0 public Test(int a) { // explicitly assign v a value v = a; } static void Main() { Test[] tests = new Test [2]; // declare array Console.WriteLine(tests[1]); // ok, elements assigned to null Test t; Console.WriteLine(t); // error, t not assigned before use } }
Parameters • A method typically has a sequence of parameters • Parameters define the set of arguments that must be provided for that method static void Foo(int p) {++p;} static void Main() { Foo(8);} • By default, arguments are passed by value: a copy is made • May pass by reference by using the “ref” keyword (referred to as ref modifier) • static void Foo(ref int p) {++p;}
Expressions and Operations • An expression is a sequence of operators and operands that specifies a computation. • C# has unary operators, binary operators, and one ternary operator. • Complex expressions can be built because an operand may itself be an expression • Example: ((1 + 2) / 3) • Operator precedence
Statements • Execution in a C# program is specified by a series of statements that execute sequentially in the textual order in which they appear • A statement may assign an expression to a variable, repeatedly execute a list of statements, or jump to another statement • Multiple statements can be grouped together, zero or more statements may be enclosed in braces to form a statement block • Many different types of statements
Expression Statements • An expression statement evaluates an expression, either assigning its result to a variable or generating side effects (i.e., invocation, new, ++, -- • An expression statement ends in a semicolon x = 5 + 6; // assign result x++; // side effect y = Math.Min(x, 20); // side effect and assign result Math.Min(x, y); // discards result, but ok, there is a side effect x == y; // error, has no side effect, does not assign result
Declaration Statements • A declaration statement declares a new variable, optionally assigning the result of an expression to that variable • A declaration statement ends in a semicolon • The scope of a local or constant variable extends to the end of the current block bool a = true; while(a) { int x = 5; if (x==5) { int y = 7; int x = 2; // error, x already defined } Console.WriteLine(y); // error, y is out of scope }
Selection Statements • Conditionally control the flow of program execution • The if-else statement: An if-else statement executes code depending on whether a boolean expression is true int Compare(int a, int b) { if (a>b) return 1; else if (a<b) return -1; return 0; } Umbrella GetUmbrella (bool rainy, bool sunny, bool windy) { if ((rainy || sunny) && ! windy) return umbrella; return null; }
Selection Statements void Award(int x) { switch(x) { case 1: Console.WriteLine(“1st class!"); break; case 2: Console.WriteLine(“2nd class"); break; default: Console.WriteLine("Don't quit"); break; } } • The switch statement: let you branch program execution based on a selection of possible values a variable may have • The switch statements can only evaluate a predefined type or enum • The end of each case statement must be unreachable • The break statement • The return statement
Loop Statements • A sequence of statements to execute repeatedly with the while, do while, for, and foreach statements • The while loop: express is tested before the block is executed • The do-while loop: express is tested at the end of block int i = 0; while (i<5) { Console.WriteLine (i); i++; } int i = 8; do { Console.WriteLine (i); i++; } while (i<5);
Loop Statements • The for loop contains three parts • A statement executed before the loop begins • A boolean expression, if true, execute the block • A statement executed after each iteration of the block • The foreach statement: works on any collection (including arrays) for (int i=0; i<10; i++) Console.WriteLine(i); foreach (Stick stick in dynamite) Console.WriteLine(stick); for (int i=0; i<dynamite.Length; i++) Console.WriteLine(dynamite [i]);
Jump Statements • Including: break, continue, return, goto, and throw • The break statement: transfer execution from the loop/switch block to the next statement • The continue statement: forgo the remaining statements in the loop, start the next iteration • The return statement: exit the method, return an expression • The goto statement: don’t use it! • The throw statement: throw an exception Umbrella GetUmbrella (bool rainy, bool sunny, bool windy) { if ((rainy || sunny) && ! windy) return umbrella; return null; }
The using Statement • The using statement provides an elegant syntax for declaring and then calling the Dispose method of variables that implement IDisposable using (FileStream fs = new FileStream (fileName,FileMode.Open)) { ... }
Namespaces namespace MyCompany { namespace MyProduct { namespace Drawing { class Point {int x, y, z;} delegate void PointInvoker(Point p); } } } • A namespace lets you group related types into a hierarchical categorization • Namespaces can be nested • Using a type with fully qualified name • Using the “using” keyword MyCompany.MyProduct.Drawing.Point x; using MyCompany.MyProduct.Drawing; class Test { static void Main() { Point x; }
Classes and Structs • Classes and structs are two of the basic constructs of the common type system • Each is a data structure that encapsulates a set of data and behaviors that belong together as a logical unit • A class or struct can specify how accessible each of its members is to code outside of the class or struct • Methods and variables that are not intended to be used from outside can be hidden to limit the potential for coding errors or malicious exploits • The data and behaviors are the members of the class or struct, and they include its methods, properties, and events, and so on
Classes and Structs • A class or struct declaration is a blueprint for creating instances or objects at run time • If you define a class or struct called Person, Person is the name of the type. • If you declare and initialize a variable p of type Person, p is said to be an object or instance of Person • Person p; • Multiple instances of the same Person type can be created, and each instance can have different values in its properties and fields
Classes and Structs • In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created • Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created
Members of a Class or Struct • Fields • Constants • Properties • Methods • Constructors • Destructors • Indexers • Delegates • Operators • Events
Members of a Class or Struct: Fields • A field is a variable of any type that is declared directly in a class or struct • A class or struct may have instance fields or static fields or both • you should use fields only for variables that have private or protected accessibility public class CalendarEntry { // private field private DateTime date; // public field (Generally not recommended) public string day;
Members of a Class or Struct: Properties • A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field • Properties can be used as if they are public data members, but they are actually special methods called accessors • This enables data to be accessed easily and still helps promote the safety and flexibility of methods
Members of a Class or Struct: Properties class TimePeriod { private double seconds; public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } } } class Program { static void Main() { // Assigning the Hours property causes the 'set' accessor to be called TimePeriod t = new TimePeriod(); // Evaluating the Hours property causes the 'get' accessor to be called t.Hours = 24; System.Console.WriteLine("Time in hours: " + t.Hours); } }
Members of a Class or Struct: Methods • Methods define the actions that a class can perform. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter class SimpleMath { public int AddTwoNumbers(int number1, int number2) { return number1 + number2; } public int SquareANumber(int number) { return number * number; } }
Members of a Class or Struct: Constructor • Whenever a class or struct is created, its constructor is called • A class or struct may have multiple constructors that take different arguments • Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read • If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values
Members of a Class or Struct: Constructor public class Taxi { public bool isInitialized; public Taxi() { isInitialized = true; } } class TestTaxi { static void Main() { Taxi t = new Taxi(); Console.WriteLine(t.isInitialized); } }
Members of a Class: Destructor • Destructors are used to destruct instances of classes • Destructors cannot be defined in structs. They are only used with classes. • A class can only have one destructor. • Destructors cannot be inherited or overloaded. • Destructors cannot be called. They are invoked automatically. • A destructor does not take modifiers or have parameters. class Car { ~Car() // destructor { // cleanup statements... } }
Members of a Class: Indexers • Indexers allow instances of a class or struct to be indexed just like arrays • Indexers resemble properties except that their accessors take parameters class SampleCollection<T> { // Declare an array to store the data elements private T[] arr = new T[100]; // Define the indexer // This indexer returns or sets the corresponding element //from the internal array public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }
Members of a Class: Indexers // This class shows how client code uses the indexer class Program { static void Main(string[] args) { // Declare an instance of the SampleCollection type SampleCollection<string> stringCollection = new SampleCollection<string>(); // Use [] notation on the type stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } } // Output: // Hello, World.
Members of a Class: Delegates • A delegate is a type that represents references to methods with a particular parameter list and return type • When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type • You can invoke the method through the delegate instance (callback method) • Delegates are used to pass methods as arguments to other methods • Event handlers are nothing more than methods that are invoked through delegates
Trying out • Creating a new project in Visual Studio • Choose Visual C# Console Application • Change project name to: CsharpPractice
Trying out • Here is what you see after the project was created • Add your code in static void Main()
Trying out • Normally, when you want to execute the program, you click the “Start Debugging” button, or F5 • However, for console app, you do not have a chance to see anything before the console is closed • You can use the trick described here: • http://www.kobashicomputing.com/running-your-console-application-within-visual-studio
Run Console App from within Visual Studio • Fisrt step: Tools/External Tools