370 likes | 384 Views
Learn about variables, parameters, expressions, statements, and loops in C# programming language. This lecture covers the basics and provides examples. C# primer II based on the book "C# in a Nutshell" and the C# Programming Guide.
E N D
EEC-492/592Kinect Application Development Lecture 5 C# Primer II Wenbing Zhao wenbing@ieee.org
Outline C# primer II 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
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)
Array Element Initialization • When any type of array is created, each of the elements is automatically initialized to the default value for the type • The default values for the predefined types are • 0 for integer types • 0.0 for floating point types • false for Booleans, and • null for reference types EEC492/693/793 - iPhone Application Development
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: expression is tested before the block is executed • The do-while loop: expression 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
Run Console App from within Visual Studio • Click the Add button to create a new entry • Enter in the new title for your console app => will appear in the Tools menu (CsharpPractice) • Click the … button and select the executable to run • Click the “Use Output” window and “Prompt for arguments” checkboxes
Run Console App from within Visual Studio • Head over to the Tools menu and you will see your console app as a menu item