47
Core C# and OO Jussi Pohjolainen Tampere University of Applied Sciences

Core C#

Embed Size (px)

Citation preview

Page 1: Core C#

Core  C#  and  OO  

Jussi  Pohjolainen  Tampere  University  of  Applied  Sciences  

Page 2: Core C#

CORE  C#  

Page 3: Core C#

Parameter  Passing  in  C#  

•  Value  types  – Built-­‐in  primiBve  types,  such  as  char,  int  float  etc  –  (Although  these  are  objects)  

•  Reference  types  – Classes  

•  But  value  types  can  be  passes  also  as  reference!  

Page 4: Core C#

Passing  Values  

•  Default  manner  in  parameters:  by  value  •  You  can  change  this  by  using  parameter  modifiers  – out  –  pass  by  reference,  parameter  can  be  unini3alized  

–  ref  –  pass  by  reference,  parameter  must  be  ini3alized  

– params  –  number  of  arguments  

Page 5: Core C#

static void Main() { int answer; // Pass answer as reference! calculate(5, 5, out answer); Console.Write(answer); int x; int y; int z; // Pass these as reference! fillThese(out x, out y, out z); } static void calculate(int a, int b, out int answer) { answer = a + b; } static void fillThese(out int a, out int b, out int c) { a = 8; b = 10; c = 12; }

Page 6: Core C#

static void Main() { int answer1; // You must initialize this! int answer2 = -1; // Pass answer as reference! Calculate1(5, 5, out answer1); // Pass answer as reference! Calculate2(5, 5, ref answer2); } static void Calculate1(int a, int b, out int answer) { answer = a + b; } static void Calculate2(int a, int b, ref int answer) { answer = a + b; }

Page 7: Core C#

static void Main() {

Car car = new Car();

car.name = "BMW";

// Now name is Skoda

ChangeName1(car);

Console.WriteLine(car.name);

// Now name is Audi

ChangeName2(out car);

Console.WriteLine(car.name);

// Now name is Skoda

ChangeName3(ref car);

Console.WriteLine(car.name);

}

static void ChangeName1(Car c) {

c.name = "Skoda";

}

static void ChangeName2(out Car c) {

// This does not work:

// c.name = "Audi";

// Why? Because it's possible that c is not initialized!

// This works:

c = new Car();

c.name = "Audi";

}

static void ChangeName3(ref Car c) {

c.name = "Skoda";

}

Page 8: Core C#

Params  Modifier  using System; class Test { static void Main() { DoSomething(); DoSomething(0); DoSomething(0,1,2,3); double [] values = {1,2,3}; DoSomething(values); } static void DoSomething(params double[] values) { for(int i=0; i<values.Length; i++) { Console.WriteLine(values[i]); } } }

Page 9: Core C#

OpBonal  Parameters  using System; class Test { static void Main() { GiveFeedBackToTeacher("Sam Student"); } static void GiveFeedBackToTeacher(string studentName, string message = "Worst Course Ever", string teacher = "Jussi Pohjolainen") { Console.Beep(); Console.WriteLine("To:" + teacher); Console.WriteLine(message); } }

Page 10: Core C#

Named  Parameters  using System; class Test { static void Main() { // Using Named Parameters! You can // switch parameter places if you give the names! GiveFeedBackToTeacher(message: "Best Course Ever", studentName: "Max Power", teacher: "Paavo"); } static void GiveFeedBackToTeacher(string studentName, string message = "Worst Course Ever", string teacher = "Jussi Pohjolainen") { Console.Beep(); Console.WriteLine("To:" + teacher); Console.WriteLine(message); } }

Page 11: Core C#

Arrays   static void Main() { int [] myInts1 = {1,2,3}; print(myInts1); var myInts2 = new int[3]; print(myInts2); var myInts3 = new int[]{1,2,3}; print(myInts3); } static void print(params int [] myInts) { // foreach foreach(int i in myInts) { Console.WriteLine(i); } }

Page 12: Core C#

System.Array  •  Array  holds  methods  and  properBes:  –  Clear()  –  Sets  a  range  of  array  elements  to  zero  –  CopyTo()  –  Copies  elements  from  array  to  another  –  Length  –  Size  of  the  array  –  Rank  –  Number  of  Dimensions  (one,  two..)  –  Reverse()  –  Reverses    –  Sort()  –  Sorts  an  array,  custom  objects  also  (IComparer  interface)  

•  Lot’s  of  methods:  –  hWp://msdn.microsoY.com/en-­‐us/library/system.array.aspx  

Page 13: Core C#

enum  enum Color1 { RED, // = 0 BLUE, // = 1 GREEN // = 2 } enum Color2 { RED = 100, // = 100 BLUE, // = 101 GREEN // = 102 }

enum Color3 { RED = 100, // = 100 BLUE = 2, // = 2 GREEN = 3 // = 3 } enum Color4 : byte { RED = 100, // = 100 BLUE = 2, // = 2 GREEN = 3 // = 3 // WHITE = 999 => fail }

Page 14: Core C#

enum  class Test { static void Main() { Color1 red = Color1.RED; if(red == Color1.RED) { Console.Write("Yes!"); } // Prints RED! Console.Write(Color1.RED); } }

Page 15: Core C#

System.enum  

•  Methods  like  – GetValues()  –  Array  of  all  values  – GetUnderlyingType()  –  Datatype  of  the  enum  

•  See:  – hWp://msdn.microsoY.com/en-­‐us/library/system.enum.aspx  

Page 16: Core C#

struct  

•  Struct  is  a  lightweight  class  –  Inheritance  not  supported  

•  For  small  data  structures  •  Struct  is  passed  by  value,  classes  by  reference  •  Struct  can  contain  aWributes,  methods..  almost  all  the  things  that  are  found  in  classes  

Page 17: Core C#

struct  struct Point { public int X; public int Y; public void Increment() { X++; Y++; } public void Print() { Console.WriteLine(X); Console.WriteLine(Y); } }

Page 18: Core C#

struct  class Test { static void Main() { Point point; point.X = 12; point.Y = 99; point.Increment(); point.Print(); Point origo = point; origo.X = 0; origo.Y = 0; point.Print(); origo.Print(); } }

Page 19: Core C#

Value  Types  and  Reference  Types?  

•  int  is  a  shortcut  of  System.int32  struct  –  So  int  is  an  struct  object!  And  it’s  passed  by  value  

•  enum  is  a  shortcut  of  System.enum  class  –  Enums  are  passed  by  value.  How  come?  It’s  inherited  from  System.ValueType!  

•  System.ValueType?  –  Provides  base  class  for  value  types  – Overrides  some  funcBonality  from  System.Object  so  all  objects  created  are  put  to  stack  instead  of  heap.  

–  Special  class,  you  cannot  inherit  it.  

Page 20: Core C#

Rules:  Value  Types  

•  Value  types  are  allocated  on  stack  •  Value  types  extend  System.ValueType  •  Value  types  cannot  be  inherited  •  Value  types  are  passed  by  value  •  Cannot  add  Finalize()  method  •  You  can  define  custom  contructor  (default  is  reserved)  

•  Removed  from  memory  when  out  of  scope  

Page 21: Core C#

Nullable  Type  

•  bool  mybool  – You  can  set  values  true  or  false  

•  ?bool  mybool  – You  can  set  values  true,  false  and  null  

•  Only  legal  for  value  types!  •  Shortcut:  ??  – //  If  result  is  null,  then  assign  100  –  int  data  =  getSomething()  ??  100;  

Page 22: Core C#

OO  WITH  C#  

Page 23: Core C#

MulBple  Constructors  and  this  class Point { public int X; public int Y; public Point() : this(0,0) { } public Point(int aX) : this(aX, 0) { X = aX; } public Point(int aX, int aY) { X = aX; Y = aY; } }

Page 24: Core C#

Easier  Way  class Point { public int X; public int Y; public Point(int aX = 0, int aY = 0) { X = aX; Y = aY; } }

Page 25: Core C#

StaBc  Class    can  contain  only  staBc  content  

static class MyMath { public static double sqrt(double d) { //... return -1; } public static double abs(double d) { //... return -1; } }

Page 26: Core C#

Access  Modifiers  class Person { // Only me can access private String name; // Everybody can access public int age; // Me and my derived classes can access protected int shoeSize; // Me and my assembly can access (when creating .net library) internal string hairColor; // Me, my derived classes and my assembly can access protected internal int shirtSize; }

Page 27: Core C#

Default  Modifiers  class Person { Person() { } } <=> // notice, only public or internal allowed! // In nested classes it’s different.. internal class Person { private Person() { } } // If we want others to access public class Person { public Person() { } }

Page 28: Core C#

ProperBes  class Person

{

private string personName;

public string Name

{

get

{

return personName;

}

set

{

if(value.Length > 3)

{

personName = value;

}

}

}

}

class Test

{

static void Main()

{

Person jack = new Person();

jack.Name = "Jack";

Console.WriteLine(jack.Name);

}

}

Page 29: Core C#

ProperBes  class Person

{

private string name;

public Person(string name)

{

// WE ARE USING PROPERTIES!

Name = name;

}

public string Name {

get

{

return name;

}

set

{

if(value.Length > 3)

{

name = value;

}

}

}

}

Page 30: Core C#

AutomaBc  ProperBes  class Person

{

// automatic properties! VS: Write prop and press tab key twice!

public string Name { get; set; }

public Person(string name)

{

// WE ARE USING PROPERTIES!

Name = name;

}

}

Page 31: Core C#

Object  IniBalizaBon  Syntax  class Point { public int X { get; set; } public int Y { get; set; } } class Test { static void Main() { // Object initialization syntax! Point b = new Point() { X = 30, Y = 80 }; } }

Page 32: Core C#

Constant  Field  Data  

•  By  using  const,  you  can  define  constant  data  that  you  cannot  change  aYerwards  

 •  public const double PI = 3.14

Page 33: Core C#

read-­‐only  data  field  class Circle

{

// read-only data field

public readonly double PI;

// can initialize it in constructor, but after this

// it's constant.

public Circle(double value) {

PI = value;

}

}

Page 34: Core C#

ParBal  Types  

•  Single  class  across  mulBple  C#  files!  •  Point1.cs

–  partial class Point { public int X { get; set; } } •  Point2.cs

–  partial class Point { public int Y { get; set; } }

•  When  compiling  and  running,  only  one  class  exists  with  two  properBes  X  and  Y  

Page 35: Core C#

Inheritance  class Mammal { private readonly string name; public string Name { get { return name; } } public Mammal(string name) { this.name = name; } } class Person : Mammal { public Person(string name) : base(name) {} }

Page 36: Core C#

Sealed  sealed class Person : Mammal

{

public Person(string name) : base(name) {}

}

// Cannot do this, Person is sealed!

class SuperMan : Person

{

public SuperMan(string name) : base(name) {}

}

Page 37: Core C#

Overriding  // THIS FAILS! class Mammal { public void Talk() { Console.Write("Mambo jambo!"); } } class Person : Mammal { public void Talk() { Console.Write("Hello!"); } }

Page 38: Core C#

Overriding  // THIS FAILS! class Mammal { // You can override this public virtual void Talk() { Console.Write("Mambo jambo!"); } } class Person : Mammal { // And we are overriding public override void Talk() { Console.Write("Hello!"); } }

Page 39: Core C#

Overriding  // THIS FAILS! class Mammal { public void Talk() { Console.Write("Mambo jambo!"); } } class Person : Mammal { // And we are overriding public override void Talk() { Console.Write("Hello!"); } }

Page 40: Core C#

Overriding:  virtual  and  override  // SUCCESS! class Mammal { public virtual void Talk() { Console.Write("Mambo jambo!"); } } class Person : Mammal { // And we are overriding public override void Talk() { Console.Write("Hello!"); } }

Page 41: Core C#

Overriding:  new  // SUCCESS! class Mammal { public void Talk() { Console.Write("Mambo jambo!"); } } class Person : Mammal { // And we are overriding without virtual… public new void Talk() { Console.Write("Hello!"); } }

Page 42: Core C#

using System; class Mammal { public void Talk() { Console.WriteLine("Mambo jambo!"); } public virtual void Eat() { Console.WriteLine("Eating general stuff"); } } class Person : Mammal { public new void Talk() { Console.Write("Hello!"); } public override void Eat() { Console.WriteLine("Eating something made by sandwich artist."); } } class App { public static void Main() { Mammal mammal = new Person(); mammal.Talk(); // "Mambo Jambo" mammal.Eat(); // "Eating something..." } }

Page 43: Core C#

class Person : Mammal { public new void Talk() { Console.Write("Hello!"); } public sealed override void Eat() { Console.WriteLine("Eating something made by …"); } } class SuperMan : Person { // Cannot override a sealed method public override void Eat() { // FAIL! } }

Page 44: Core C#

class App { public static void Main() { Mammal jussi = new Person(); // Cast to Person, null if it fails. Person d = jussi as Person; if(d == null) { Console.WriteLine("Fail"); } // is = returns true or false! if(jussi is Person) { Console.WriteLine("Success!"); } } }

Page 45: Core C#

System.object  

•  Every  class  extends  System.object  •  See  – hWp://msdn.microsoY.com/en-­‐us/library/system.object.aspx  

•  Equals,  ToString,  …  

Page 46: Core C#

Interface  interface IMovable { void Start(); void Stop(); } class Person : Mammal, IMovable { public void Start() {} public void Stop() {} }

Page 47: Core C#

Abstract  Class  abstract class Mammal { abstract public void Talk(); abstract public void Eat(); } interface IMovable { void Start(); void Stop(); } class Person : Mammal, IMovable { public void Start() {} public void Stop() {} public override void Talk() {} public override void Eat() {} }