TDDD49 Programmering C# och .NET Lecture 1 - 2015

advertisement
TDDD49
Programmering C# och .NET
Lecture 1 - 2015
Johannes Schmidt, Department of Computer and Information Science (IDA), Linköping University
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
Staff
Examiner and Course leader: Johannes Schmidt
Assistants: Anders Märak Leffler, Fredrik Präntare, Björn
Kihlström, Simon Gustafsson
Course Secretary: Helene Meisinger
Director 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 Lectures
4 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 GUI
Lab3: Artificial intelligence
Lab4: 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 improvements
with 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, OOP
Lecture 2-3: Generics, Events, Delegates, LINQ
C# - origins
Programming languages preceding (and influencing) C#:
C
C++
Java
1972
1983
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.
Compiler
C/C++ code
Java/C# code
Compiler
Intermediate code
Machine code
Runtime
Machine code
Interpretation: Java vs C#
Java code
C# code
Compiler
Compiler
Java Byte Code
Common
Intermediate
Language
CIL
Java Runtime
Environment
Common Language
Runtime
Machine code
Machine code
CLR
or VES (Virtual Execution System)
Note: Specification and Runtime for CIL are called
CLI = 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
MS Compact Framework
MS XNA
Mono Project
DotGNU
Rotor
*) Source: Essential C# 5.0 by Mark Michaelis
(Mac and Windows)
(PDAs and phones)
(Xbox, Windows Vista)
(Windows, Linux and Unix)
(.NET and DotGNU.Portable.NET)
(Windows, Mac OS X and FreeBSD)
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
Java
#include <stdio.h>
int main(void)
{
printf("Hello world!");
}
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
C++
C#
#include <iostream.h>
int main(void)
{
std::cout << "Hello world!";
}
using System;
class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello world!");
}
}
Ada
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello is
begin
Put_Line ("Hello world!");
end Hello;
Predefined types
Type
Size
Range
BCL Name
Signed
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
Literal Suffix
Value types vs Reference types
Value types:
Reference types:
A variable contains the data
directly.
A variable contains a reference to
the data.
Examples:
all primitive types from last slide
and structs
Examples:
strings, arrays, objects
decimal x = 8;
decimal y = 9;
x = y; // 16 bytes of data are copied
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';
char y = 'c';
// blank
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) {
if (<boolean>) {
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?");
}
...
Loops
do
{
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
●
grouping types to an area of functionality (similar to java packages)
●
hierarchical
●
see e.g., System, System.IO, System.Console
using System;
using SpecialCar = Namespace02.Car; // alias
namespace Namespace01
{
class Car
{
public string name;
public int age;
}
namespace Namespace02
{
class Car
{
public string name;
}
}
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";
}
}
}
Passing arguments by reference or value
Passing by 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;
}
does not affect the assigned values in the caller.
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 affect the assigned values in the caller.
Returning more than one value
Calling code:
public int GetMax(int[] values)
{
return values.Max();
}
a = GetMax(myArray);
Returning two values via references
public void GetMinMax(int[] values, ref int max, ref int min)
{
max = values.Max();
min = values.Min();
}
GetMinMax(myArray, ref a, ref b);
Better: use the out keyword
public void GetMinMax(int[] values, out int max, out int min)
{
max = values.Max();
min = values.Min();
}
GetMinMax(myArray, out a, out b);
OOP
A 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 Karlsson
Salary: 14000
Name: Nils Nilsson
Salary: 23000
OOP – access modifiers
class Example
{
public int a;
private int b;
protected int c;
internal int d;
//
//
//
//
access
access
access
access
from
only
from
from
public void PrintInfo()
{
System.Console.WriteLine("a:
System.Console.WriteLine("b:
System.Console.WriteLine("c:
System.Console.WriteLine("d:
}
}
"
"
"
"
everywhere
from inside the class
inside the class and subclasses (inherited classes)
everywhere within the same assembly
+
+
+
+
a);
b);
c);
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 only
public string Title
{
set
{
_Title = value;
}
}
private string _Title;
// read only
public string Comment
{
get
{
return _Comment;
}
}
private string _Comment;
// from ouside the class: read only
// inside: read and write access
public 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; }
}
In C# only single inheritance!
class Program
{
static void Main(string[] args)
{
PdaItem PdaItem = new PdaItem();
Contact Contact = new Contact();
PdaItem = Contact;
Contact = (Contact)PdaItem;
}
}
// implicit conversion
// explicit conversion required via casting
OOP – overriding methods or properties
Use 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 classes
Abstract 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();
Vehicle c = new Car();
}
}
// you can not instantiate from an abstract class!
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 the
current object.
public virtual bool Equals(Object, Object)
Determines whether the specified object instances are
considered 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 are
the 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 perform
other cleanup operations before it is reclaimed by
garbage 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);
Console.WriteLine(data2 is string);
// True
// False
OOP – Interfaces
Interfaces 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:
Implementation:
interface IListable
{
string[] Values
{
get;
}
}
class Contact : PdaItem, IListable
{
public string FirstName;
public string LastName;
public string Address;
}
You can implement
multiple interfaces.
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);
}
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.
Download