SlideShare una empresa de Scribd logo
1 de 47
Descargar para leer sin conexión
Core	
  C#	
  and	
  OO	
  

            Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
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!	
  
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	
  
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;
   }
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;
   }
static void Main() {                  static void ChangeName2(out Car c) {
       Car car = new Car();                  // This does not work:
       car.name = "BMW";                     //   c.name = "Audi";
                                             // Why? Because it's possible that c is not initialized!
       // Now name is Skoda                  // This works:
       ChangeName1(car);                     c = new Car();
       Console.WriteLine(car.name);          c.name = "Audi";
                                         }
       // Now name is Audi
       ChangeName2(out car);            static void ChangeName3(ref Car c) {
       Console.WriteLine(car.name);         c.name = "Skoda";
                                        }
       // Now name is Skoda
       ChangeName3(ref car);
       Console.WriteLine(car.name);
   }

   static void ChangeName1(Car c) {
       c.name = "Skoda";
   }
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]);
        }
    }
}
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);
    }
}
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);
    }
}
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);
       }
   }
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	
  
enum	
  
enum Color1                      enum Color3
{                                {
    RED,    // = 0                   RED   = 100, // = 100
    BLUE, // = 1                     BLUE = 2,    // = 2
    GREEN // = 2                     GREEN = 3    // = 3
}                                }

enum Color2                      enum Color4 : byte
{                                {
    RED = 100,    // = 100           RED   = 100, //   = 100
    BLUE,         // = 101           BLUE = 2,    //   = 2
    GREEN         // = 102           GREEN = 3    //   = 3
}                                    // WHITE = 999    => fail
                                 }
enum	
  
class Test
{
    static void Main() {
        Color1 red = Color1.RED;
        if(red == Color1.RED)
        {
            Console.Write("Yes!");
        }

        // Prints RED!
        Console.Write(Color1.RED);
    }
}
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	
  
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	
  
struct	
  
struct Point {
    public int X;
    public int Y;

    public void Increment() {
        X++; Y++;
    }

    public void Print() {
        Console.WriteLine(X);
        Console.WriteLine(Y);
    }
}
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();
    }
}
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.	
  
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	
  
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;	
  
OO	
  WITH	
  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;
    }
}
Easier	
  Way	
  
class Point
{
    public int X;
    public int Y;

    public Point(int aX = 0, int aY = 0)
    {
        X = aX;
        Y = aY;
    }
}
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;
    }
}
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;
}
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() { }
}
ProperBes	
  
class Person                             class Test
{                                        {
    private string personName;               static void Main()
                                             {
    public string Name                           Person jack = new Person();
    {                                            jack.Name = "Jack";
        get                                      Console.WriteLine(jack.Name);
        {                                    }
            return personName;           }
        }

        set
        {
              if(value.Length > 3)
              {
                  personName = value;
              }
        }
    }
}
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;
             }
        }
    }
}
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;
    }
}
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 };
    }
}
Constant	
  Field	
  Data	
  
•  By	
  using	
  const,	
  you	
  can	
  define	
  constant	
  data	
  
     that	
  you	
  cannot	
  change	
  aYerwards	
  
	
  
•  public const double PI = 3.14
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;
    }
}
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	
  
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) {}
}
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) {}
}
Overriding	
  
// THIS FAILS!
class Mammal
{
    public void Talk()
    {
        Console.Write("Mambo jambo!");
    }
}

class Person : Mammal
{
    public void Talk()
    {
        Console.Write("Hello!");
    }

}
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!");
    }

}
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!");
    }

}
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!");
    }
}
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!");
    }
}
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..."
    }
}
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!
    }
}
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!");
        }
    }
}
System.object	
  
•  Every	
  class	
  extends	
  System.object	
  
•  See	
  
    –  hWp://msdn.microsoY.com/en-­‐us/library/
       system.object.aspx	
  
•  Equals,	
  ToString,	
  …	
  
Interface	
  
interface IMovable
{
    void Start();
    void Stop();
}

class Person : Mammal, IMovable
{
    public void Start() {}
    public void Stop() {}
}
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() {}
}

Más contenido relacionado

La actualidad más candente

One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersEelco Visser
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does notSergey Bandysik
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in ScalaDamian Jureczko
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionEelco Visser
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 

La actualidad más candente (20)

One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
C# programming
C# programming C# programming
C# programming
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax Definition
 
Java introduction
Java introductionJava introduction
Java introduction
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 

Destacado

StephenRadioDramaOutlineFordraft.docx
StephenRadioDramaOutlineFordraft.docxStephenRadioDramaOutlineFordraft.docx
StephenRadioDramaOutlineFordraft.docxStephen Hilton
 
Planes comparativo
Planes comparativoPlanes comparativo
Planes comparativoalejandro004
 
1 Despre Intreprinderile Mici Si Mijlocii
1 Despre Intreprinderile Mici Si Mijlocii1 Despre Intreprinderile Mici Si Mijlocii
1 Despre Intreprinderile Mici Si MijlociiNiceTimeGo
 
Brad Hunter 30 Cities In 30 Minutes
Brad Hunter 30 Cities In 30 MinutesBrad Hunter 30 Cities In 30 Minutes
Brad Hunter 30 Cities In 30 MinutesRyan Slack
 
Futurecom - Brad Bush Keynote - Limitless Realtime Communications
Futurecom - Brad Bush Keynote - Limitless Realtime CommunicationsFuturecom - Brad Bush Keynote - Limitless Realtime Communications
Futurecom - Brad Bush Keynote - Limitless Realtime CommunicationsBrad Bush
 
Static vs dynamic types
Static vs dynamic typesStatic vs dynamic types
Static vs dynamic typesTerence Parr
 
Static and dynamic characters
Static and dynamic charactersStatic and dynamic characters
Static and dynamic characterselissajac
 

Destacado (13)

StephenRadioDramaOutlineFordraft.docx
StephenRadioDramaOutlineFordraft.docxStephenRadioDramaOutlineFordraft.docx
StephenRadioDramaOutlineFordraft.docx
 
Planes comparativo
Planes comparativoPlanes comparativo
Planes comparativo
 
1 Despre Intreprinderile Mici Si Mijlocii
1 Despre Intreprinderile Mici Si Mijlocii1 Despre Intreprinderile Mici Si Mijlocii
1 Despre Intreprinderile Mici Si Mijlocii
 
Brad Hunter 30 Cities In 30 Minutes
Brad Hunter 30 Cities In 30 MinutesBrad Hunter 30 Cities In 30 Minutes
Brad Hunter 30 Cities In 30 Minutes
 
Polícia 2 0
Polícia 2 0Polícia 2 0
Polícia 2 0
 
Futurecom - Brad Bush Keynote - Limitless Realtime Communications
Futurecom - Brad Bush Keynote - Limitless Realtime CommunicationsFuturecom - Brad Bush Keynote - Limitless Realtime Communications
Futurecom - Brad Bush Keynote - Limitless Realtime Communications
 
Ud6: De la emergencia planetaria a la construcción de un futuro sostenible
Ud6: De la emergencia planetaria a la construcción de un futuro sostenibleUd6: De la emergencia planetaria a la construcción de un futuro sostenible
Ud6: De la emergencia planetaria a la construcción de un futuro sostenible
 
Static vs dynamic types
Static vs dynamic typesStatic vs dynamic types
Static vs dynamic types
 
Static and dynamic characters
Static and dynamic charactersStatic and dynamic characters
Static and dynamic characters
 
Types of Characters
Types of CharactersTypes of Characters
Types of Characters
 
Static vs dynamic
Static vs dynamicStatic vs dynamic
Static vs dynamic
 
2
22
2
 
Derecho+internacional
Derecho+internacionalDerecho+internacional
Derecho+internacional
 

Similar a Core C#

Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
Type script by Howard
Type script by HowardType script by Howard
Type script by HowardLearningTech
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by HowardLearningTech
 
Howard type script
Howard   type scriptHoward   type script
Howard type scriptLearningTech
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questionsFarag Zakaria
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 

Similar a Core C# (20)

Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Type script by Howard
Type script by HowardType script by Howard
Type script by Howard
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
 
Howard type script
Howard   type scriptHoward   type script
Howard type script
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Kotlin
KotlinKotlin
Kotlin
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Parameters
ParametersParameters
Parameters
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java Generics
Java GenericsJava Generics
Java Generics
 

Más de Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

Más de Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

Core C#

  • 1. Core  C#  and  OO   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 3. 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!  
  • 4. 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  
  • 5. 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; }
  • 6. 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; }
  • 7. static void Main() { static void ChangeName2(out Car c) { Car car = new Car(); // This does not work: car.name = "BMW"; // c.name = "Audi"; // Why? Because it's possible that c is not initialized! // Now name is Skoda // This works: ChangeName1(car); c = new Car(); Console.WriteLine(car.name); c.name = "Audi"; } // Now name is Audi ChangeName2(out car); static void ChangeName3(ref Car c) { Console.WriteLine(car.name); c.name = "Skoda"; } // Now name is Skoda ChangeName3(ref car); Console.WriteLine(car.name); } static void ChangeName1(Car c) { c.name = "Skoda"; }
  • 8. 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]); } } }
  • 9. 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); } }
  • 10. 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); } }
  • 11. 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); } }
  • 12. 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  
  • 13. enum   enum Color1 enum Color3 { { RED, // = 0 RED = 100, // = 100 BLUE, // = 1 BLUE = 2, // = 2 GREEN // = 2 GREEN = 3 // = 3 } } enum Color2 enum Color4 : byte { { RED = 100, // = 100 RED = 100, // = 100 BLUE, // = 101 BLUE = 2, // = 2 GREEN // = 102 GREEN = 3 // = 3 } // WHITE = 999 => fail }
  • 14. enum   class Test { static void Main() { Color1 red = Color1.RED; if(red == Color1.RED) { Console.Write("Yes!"); } // Prints RED! Console.Write(Color1.RED); } }
  • 15. 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  
  • 16. 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  
  • 17. struct   struct Point { public int X; public int Y; public void Increment() { X++; Y++; } public void Print() { Console.WriteLine(X); Console.WriteLine(Y); } }
  • 18. 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(); } }
  • 19. 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.  
  • 20. 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  
  • 21. 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;  
  • 23. 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; } }
  • 24. Easier  Way   class Point { public int X; public int Y; public Point(int aX = 0, int aY = 0) { X = aX; Y = aY; } }
  • 25. 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; } }
  • 26. 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; }
  • 27. 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() { } }
  • 28. ProperBes   class Person class Test { { private string personName; static void Main() { public string Name Person jack = new Person(); { jack.Name = "Jack"; get Console.WriteLine(jack.Name); { } return personName; } } set { if(value.Length > 3) { personName = value; } } } }
  • 29. 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; } } } }
  • 30. 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; } }
  • 31. 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 }; } }
  • 32. Constant  Field  Data   •  By  using  const,  you  can  define  constant  data   that  you  cannot  change  aYerwards     •  public const double PI = 3.14
  • 33. 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; } }
  • 34. 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  
  • 35. 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) {} }
  • 36. 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) {} }
  • 37. Overriding   // THIS FAILS! class Mammal { public void Talk() { Console.Write("Mambo jambo!"); } } class Person : Mammal { public void Talk() { Console.Write("Hello!"); } }
  • 38. 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!"); } }
  • 39. 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!"); } }
  • 40. 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!"); } }
  • 41. 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!"); } }
  • 42. 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..." } }
  • 43. 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! } }
  • 44. 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!"); } } }
  • 45. System.object   •  Every  class  extends  System.object   •  See   –  hWp://msdn.microsoY.com/en-­‐us/library/ system.object.aspx   •  Equals,  ToString,  …  
  • 46. Interface   interface IMovable { void Start(); void Stop(); } class Person : Mammal, IMovable { public void Start() {} public void Stop() {} }
  • 47. 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() {} }