tddd49tddd49/forelasningar/lecture01_2015.pdf · in this lecture: organisation introduction to c#...
TRANSCRIPT
In this lecture:● Organisation● Introduction to C# and .NET● Basic syntax and constructs, OOP● namespaces, ref, out● More OOP: properties, constructor, inheritance, override, abstract classes,
System.Object, interfaces
TDDD49Programmering C# och .NETLecture 1 - 2015Johannes Schmidt, Department of Computer and Information Science (IDA), Linköping University
Staff
Examiner and Course leader: Johannes SchmidtAssistants: Anders Märak Leffler, Fredrik Präntare, Björn Kihlström, Simon GustafssonCourse Secretary: Helene MeisingerDirector of studies: Jalal Maleki
Question
Who knows C, C++ or Java?
Who does not?
Another question
Who is from the course 725G66?
Purpose
● tillämpa och reflektera över C#s språkkonstruktioner och deras semantik, t.ex. klasser, delegater, event, nätverk för att bygga objektorienterade program.
● tillämpa och reflektera över olika centrala delar av .NET Framework t.ex. ASP.NET, ADO.NET, Windows Presentation Foundation (WPF) för att bygga applikationer
● tillämpa och reflektera över utvecklingsmiljö som Visual Studio.
Organisation
3 Lectures4 Labassignments (connected)13 assisted lab sessions scheduled
107 hours of work => you work a lot on your own
Examination elements:LAB1 4 poäng - Laborationer (U,G)
Course page http://www.ida.liu.se/~TDDD49/
Lab Organisation
Work in pairs or individually. Location: PC1, PC2, PC3
Sign up in Webreg mandatory:
https://www.ida.liu.se/webreg3/TDDD49-2015-1/LAB1
https://www.ida.liu.se/webreg3/725G66-2015-1/LAB1
Registration Deadline: Nov. 11th
Webreg sign up is only possible if you are registered for the course.
Lab assignments
Subject: Board games! (Monopoly, Mastermind, Chess, Poker, …)Tic-tac-toe: too small
Lab1: Game Engine (rules, logic)Lab2: Develop the GUILab3: Artificial intelligenceLab4: Synchronized storage (use LINQ).(See course page for more details http://www.ida.liu.se/~TDDD49/)
Lab assessment
Do the labs stepwise or all in one.In any case, planning is required before you start coding.You are welcome to check your plan with your lab assistant.
Important: use one of the IDEs Visual Studio, Xamarin, MonoDevelop.
If you plan to use MonoDevelop, you should choose Björn Kihlström as assistant.
Demo and oral examination are mandatory before a final submission can be accepted.
Final submission: via box (invitations will be send out soon).
Course's improvementswith respect to last year
- lectures: 3 condensed lectures instead of 4- lectures: more information on the labs- lectures: more on LINQ- labs: more clear instructions and requirements- labs: several examination periods instead of one deadline: week 49, 51 and week 2 During these weeks examination/demo has priority. During the other weeks assistance has priority. Results will be reported in week 50 and in week 3.
Lectures - Outline
Lecture 1: Intro to C# and .NET, basic syntax and constructs, OOPLecture 2-3: Generics, Events, Delegates, LINQ
C# - origins
Programming languages preceding (and influencing) C#:
C 1972C++ 1983Java 1995
C# 2000 // syntax very similar to C, C++, Java.
Ada 1980 // looks different.
Compilation vs Interpretation
C and C++ are compiled directly to machine code (unmanaged code).
Java and C# are compiled to an intermediate code (managed code).For excecution a special Runtime is needed.
C/C++ code Machine code
Machine codeJava/C# code Intermediate code
Compiler
Compiler Runtime
Interpretation: Java vs C#
Machine codeC# codeCommon
Intermediate Language
Compiler
Machine codeJava code Java Byte CodeCompiler Java Runtime
Environment
Common LanguageRuntime
CIL CLRor VES (Virtual Execution System)
Note: Specification and Runtime for CIL are calledCLI = Common Language Infrastructure
What is .NET?Predominant implementation of the Common Language Infrastructure (CLI)From: Microsoft (MS)Target Platforms: MS Windows
Other implementations exist*), e.g.:
MS Silverlight (Mac and Windows)MS Compact Framework (PDAs and phones)MS XNA (Xbox, Windows Vista)Mono Project (Windows, Linux and Unix)DotGNU (.NET and DotGNU.Portable.NET)Rotor (Windows, Mac OS X and FreeBSD)
*) Source: Essential C# 5.0 by Mark Michaelis
What provides a CLI implementation such as .NET?
● Garbage collection● Type safty (based on Common Type System CTS)● Code Access Security● Base Class Library (BCL) and platformspecific libraries*)
● Language interoperability (C#, Visual Basic, F#, …)● Platform portability (theoretically...)
*) for instance Framework Class Library FCL (.NET)
.NET
Hello World!
C
#include <stdio.h>int main(void){
printf("Hello world!");}
C++
#include <iostream.h>int main(void){
std::cout << "Hello world!";}
Java
class HelloWorld {public static void main(String[] args) {
System.out.println("Hello world!");}
}
C#
using System;class HelloWorld{ static void Main() { Console.WriteLine("Hello world!"); }}Ada
with Ada.Text_IO; use Ada.Text_IO;procedure Hello isbegin Put_Line ("Hello world!");end Hello;
Predefined typesType Size Range BCL Name Signed Literal Suffix
sbyte 8 bits -128 to 127 System.SByte Yes
byte 8 bits 0 to 255 System.Byte No
short 16 bits -32,768 to 32,767 System.Int16 Yes
ushort 16 bits 0 to 65,535 System.UInt16 No
int 32 bits -2,147,483,648 to 2,147,483,647
System.Int32 Yes
uint 32 bits 0 to 4,294,967,295 System.UInt32 No U or u
long 64 bits -9.2e18 to 9.2e18 System.Int64 Yes L or l
ulong 64 bits 18.4e18 System.UInt64 No UL or ul
float 32 bits +-1.5e-45 to +-3.4e38 System.Single Yes F or f
double 64 bits +-5.0e-324 to +-1.7e308 System.Double Yes D or d
decimal 128 bits +-1.0e-28 to +-7.9e28 System.Decimal Yes M or m
char 16 bits 65536 characters System.Char
bool 8 bits true or false System.Boolean
All these types are value types
Value types vs Reference types
Value types:
A variable contains the data directly.
Examples:all primitive types from last slideand structs
decimal x = 8;decimal y = 9;x = y; // 16 bytes of data are copied
Reference types:
A variable contains a reference to the data.
Examples:strings, arrays, objects
string a = "abc";string b = "abracadabra";a = b; // only a reference is copied // (typically 4-8 bytes)
Declarations
int myInteger;myInteger = 1;int yourTnteger = 0;
char x;x = '\u0020'; // blankchar y = 'c';
float height1;height1 = 1.443F;float height2 = float.Parse("1.222");
string s;s = "def";string t = "abc";
int[] values;values = new int[] { 3, 2, 7, 18 };int[] more = { 4, 5, 6 };int[] evenmore = new int[100];
int count = more.Length; // will be 3
Conditions
if (more.Length == 14) {
evenmore[0] += 22;
}
if (more.Length < 10) {
evenmore[0] += 22;
} else {
evenmore[2] = -17;
}
if (more.Length < 10) {
evenmore[0] += 22;
} else if(more.Length > 102) {
evenmore[1] = 8;
} else {
System.Console.WriteLine("why?");
}
if (<boolean>) {
...
}
Loopsdo{
a = int.Parse(System.Console.ReadLine());}while (a != 0);
while (a < 10){
System.Console.WriteLine("Here is your integer: {0}\n", a);a++;
}
for (a = 0; a < 10; a++){
System.Console.WriteLine("Counting...\n");}
foreach(int x in values){
if(x > currentMax){
currentMax = x;
}
}
Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
+, -, *, / Arithmetic operators
% Rest of integer division (Remainder)
<, <=, ==, !=, >=, > Comparing operators
++x, x++, --i, i-- Pre- and post-incrementing / decrementing
Operator Meaning
|, &, ^ Binary OR, AND, XOR
<< Binary leftshift
>> Binary rightshift
Methods (functions)
public int computeMax(int[] values)
{
int currentMax = values[0];
foreach(int x in values){
if(x > currentMax){
currentMax = x;
}
}
return currentMax;
}
Objects
Everything in C# is in a class.
Nothing exists without a class.
A class is a template for an object.
An object has fields (data) and methods (functions).
Recall HelloWorld:
using System;class HelloWorld{ static void Main() { Console.WriteLine("Hello world!"); }}
This class declares no fields, only one method (Main).
Objects
class Employee{ private string FirstName; private string LastName;
public string GetName() { return string.Concat(FirstName, " ", LastName); }}
2 fields
1 method
Namespaces
using System;using SpecialCar = Namespace02.Car; // alias
namespace Namespace01{ class Car { public string name; public int age; }
class Program { static void Main(string[] args) { Namespace02.Car carA = new Namespace02.Car(); Car carB = new Car(); SpecialCar carC = new SpecialCar();
System.Console.WriteLine("Abraham"); Console.WriteLine("Bebraham"); // possible due to the "using System"; } }}
namespace Namespace02{ class Car { public string name; }}
● grouping types to an area of functionality (similar to java packages)● hierarchical● see e.g., System, System.IO, System.Console
Passing arguments by reference or value
public void Swap(int a, int b){ int temp = a; a = b; b = temp;}
public void Swap(string a, string b){ string temp = a; a = b; b = temp;}
Passing by value
Passing by reference
public void SwapRef(ref int a, ref int b){ int temp = a; a = b; b = temp;}
public void SwapRef(ref string a, ref string b){ string temp = a; a = b; b = temp;}
does not affect the assigned values in the caller.
does affect the assigned values in the caller.
Returning more than one value
public int GetMax(int[] values){ return values.Max();}
Better: use the out keyword
public void GetMinMax(int[] values, out int max, out int min){ max = values.Max(); min = values.Min();}
Returning two values via references
public void GetMinMax(int[] values, ref int max, ref int min){ max = values.Max(); min = values.Min();}
GetMinMax(myArray, out a, out b);
GetMinMax(myArray, ref a, ref b);
Calling code:
a = GetMax(myArray);
OOPA class is a template for an object.
Several (different) objects can be instantiated from a class.
class Employee{ public string Name; public int Salary;
public void PrintInfo() { Console.WriteLine("Name: " + Name); Console.WriteLine("Salary: {0}", Salary); } public void IncreaseSalary(int amount) { Salary += amount; } public void SetSalary(int salary) { this.Salary = salary; }}
Employee employee1 = new Employee();Employee employee2;
employee1.Name = "Karl Karlsson";employee1.Salary = 14000;employee1.PrintInfo();
employee2 = new Employee();employee2.Name = "Nils Nilsson";employee2.Salary = 20000;employee2.IncreaseSalary(3000);employee2.PrintInfo();
Output:
Name: Karl KarlssonSalary: 14000Name: Nils NilssonSalary: 23000
OOP – access modifiers
class Example{ public int a; // access from everywhere private int b; // access only from inside the class protected int c; // access from inside the class and subclasses (inherited classes) internal int d; // access from everywhere within the same assembly
public void PrintInfo() { System.Console.WriteLine("a: " + a); System.Console.WriteLine("b: " + b); System.Console.WriteLine("c: " + c); System.Console.WriteLine("d: " + d); }}
OOP – properties
Property: behaves from the outside as a field. But is more complex.
public string FirstName // property name{ get { return _FirstName; } set { _FirstName = FirstName; }}private string _FirstName; // backing field
OOP – properties
Property: behaves from the outside as a field. But is more complex.
public string FirstName // property name{ get { return _FirstName; } set { if (value != null) { _FirstName = value; } else { _FirstName = ""; } }}private string _FirstName; // backing field
OOP – properties
Property: behaves from the outside as a field. But is more complex.
Motivation for properties:● public is often too open / dangerous for a field.● but private/protected is too restrictive● avoid hassle with getters and setters
Property features:● read-only (without getter setter methods)● write-only (without getter setter methods)● a property can not be passed as a reference● different access modifiers for read and write access
When to use a property, when a field?● Property: if simple access to data and no complex computation.● Otherwise field with getter and setter.
Basic rule: avoid public/protected. Make it a propery instead.
OOP – properties
// write onlypublic string Title{ set { _Title = value; }}private string _Title;
// read onlypublic string Comment{ get { return _Comment; }}private string _Comment;
// from ouside the class: read only// inside: read and write accesspublic string Description{ get { return _Description; } private set { _Description = value; }}private string _Description;
OOP – properties
// a propery as virtual field (i.e. without backing field)public string Name{ get { return FirstName + " " + LastName; } set { string[] names; names = value.Split((new char[] { ' ' })); FirstName = names[0]; LastName = names[1]; }}
OOP – constuctor
class Employee{ public string Name; public int Salary;
// Constructor with two parameters (overloading the constructor) public Employee(string name, int salary) { Name = name; Salary = salary; }
// Overriding the default constructor public Employee() { Name = ""; Salary = 0; }
// note: as soon as you define ANY constructor, // the default constructor is no longer available}
OOP – inheritance
class PdaItem{ public string Name { get; set; } public DateTime LastUpdated { get; set; }}
class Contact : PdaItem{ public string Address { get; set; } public string Phone { get; set; }}
class Program{
static void Main(string[] args) { PdaItem PdaItem = new PdaItem(); Contact Contact = new Contact();
PdaItem = Contact; // implicit conversion Contact = (Contact)PdaItem; // explicit conversion required via casting }}
In C# only single inheritance!
OOP – overriding methods or propertiesUse virtual to make a method or property overridable (otherwise no overriding possible).Use override when overriding (mandatory).
class PdaItem { public virtual string Name { get; set; } }
class Contact : PdaItem { public override string Name { get { return FirstName + " " + LastName; } set { string[] names = value.Split(' '); FirstName = names[0]; LastName = names[1]; } } public string FirstName { get; set; } public string LastName { get; set; } }
You can not override fields!
OOP – avoid inheritance
// sealed corresponds to final in Java
sealed class PdaItem { public string Name { get; set; } public DateTime LastUpdated { get; set; } }
// does not compile! class Contact : PdaItem { public string Address { get; set; } public string Phone { get; set; } }
OOP – avoid overriding
class A { public virtual void Method() {
} }
class B : A { public override sealed void Method() {
} }
class C : B { // does not compile! public override void Method() {
} }
OOP – base class
class A{ public virtual void Method() { Console.WriteLine("Honolulu"); }}
class B : A{ public override void Method() { base.Method(); Console.WriteLine("+ Luluhono"); }}
OOP – abstract classesAbstract classes
● represent abstract entities.● can not be instantiated, only derived● have abstract members which have to be implemented (overridden) by derived classes.
abstract class Vehicle{ int ID; public abstract void Drive();}
class Car : Vehicle{ public override void Drive() { Console.WriteLine("Driving"); }}
class Program{ static void Main(string[] args) { // Vehicle v = new Vehicle(); // you can not instantiate from an abstract class! Vehicle c = new Car(); }}
OOP – System.Object
Every class inherits from object (System.Object) the following methods:
Name Description
public virtual bool Equals(Object) Determines whether the specified object is equal to thecurrent object.
public virtual bool Equals(Object, Object) Determines whether the specified object instances areconsidered equal.
public virtual int GetHashCode() Serves as the default hash function.
public Type GetType() Gets the Type of the current instance.
public static bool ReferenceEquals() Determines whether the specified object instances arethe same instance.
public virtual string ToString() Returns a string that represents the current object.
protected virtual void Finalize() Allows an object to try to free resources and performother cleanup operations before it is reclaimed bygarbage collection.
protected Object MemberwiseClone() Creates a shallow copy of the current Object.
OOP – check type with is
class Car{ int NumWheels = 4;}
static void Main(string[] args){ object data = "Timbuktu"; object data2 = new Car();
Console.WriteLine(data is string); // True Console.WriteLine(data2 is string); // False}
OOP – InterfacesInterfaces are contracts.
A class implementing an interface "promises" to implement certain methods.
Declaration as a class, but contains only declarations no definitions.And only methods or properties. No fields.
Declaration:
interface IListable{ string[] Values { get; }}
Implementation:
class Contact : PdaItem, IListable{ public string FirstName; public string LastName; public string Address;
public string[] Values { get { return new string[] { FirstName, LastName, Address }; } }}
Usage:
Contact Contact = new Contact() { FirstName = "Hans", LastName = "Hansson", Address = "Kungsgatan"};
foreach(string s in Contact.Values){
Console.WriteLine(s);}
You can implementmultiple interfaces.
Literature and useful links
Books on C#:
Essential C# 5.0 by Mark Michaelis (with Eric Lippert) (language focused)
Head first C# by Andrew Stellman and Jennifer Greene (Visual Studio and GUI)
Links:
http://msdn.microsoft.com/ (Reference, no Tutorial)
http://msdn.microsoft.com/en-us/library/w0x726c2%28v=vs.110%29.aspx (.NET)
http://msdn.microsoft.com/en-us/vstudio/hh341490.aspx (Visual C# references)
http://msdn.microsoft.com/en-us/vstudio//bb798022.aspx (Visual C# Videos)
http://code.msdn.microsoft.com/ (Code samples)
http://msdn.microsoft.com/en-us/library/ms754130(v=vs.100).aspx (WPF)
The web.