• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
C# for C++ programmers
 

C# for C++ programmers

on

  • 3,056 views

 

Statistics

Views

Total Views
3,056
Views on SlideShare
3,055
Embed Views
1

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 1

http://www.techgig.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    C# for C++ programmers C# for C++ programmers Presentation Transcript

    • C# for C++ Programmers
      A crash course
    • C#: the basics
      Lots of similarities with C++
      Object-oriented
      Classes, structs, enums
      Familiar basic types: int, double, bool,…
      Familiar keywords: for, while, if, else,…
      Similar syntax: curly braces { }, dot notation,…
      Exceptions: try and catch
    • C#: the basics
      Actually much more similar to Java
      Everything lives in a class/struct (no globals)
      No pointers! (so no ->, * or & notation)
      Garbage collection: no delete!
      No header files
      No multiple inheritance
      Interfaces
      Static members accessed with . (not ::)
      In a nutshell: much easier than C++ 
    • Hello, world!
      using System;
      // Everything's in a namespace
      namespace HelloWorldApp
      {
      // A simple class
      class Program
      {
      // A simple field: note we can instantiate it on the same line
      private static String helloMessage = "Hello, world!";
      // Even Main() isn't global!
      static void Main(string[] args)
      {
      Console.WriteLine(helloMessage);
      }
      }
      }
    • C# features
      Properties
      Interfaces
      The foreach keyword
      The readonly keyword
      Parameter modifiers: ref and out
      Delegates and events
      Instead of callbacks
      Generics
      Instead of templates
    • Properties
      Class members, alongside methods and fields
      “field” is what C# calls a member variable
      Properties “look like fields, behave like methods”
      By convention, names are in UpperCamelCase
      Very basic example on next slide
    • Properties: simple example
      class Thing
      {
      // Private field (the “backing field”)
      private String name;
      // Public property
      public String Name
      {
      get
      {
      return name;
      }
      set
      {
      // "value" is an automatic
      // variable inside the setter
      name = value;
      }
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      Thing t = new Thing();
      // Use the setter
      t.Name = "Fred";
      // Use the getter
      Console.WriteLine(t.Name);
      }
      }
    • Properties
      So far, looks just like an over-complicated field
      So why bother?
    • Properties: advanced getter/setter
      class Thing
      {
      // Private field (the “backing field”)
      private String name;
      private static intrefCount = 0;
      // Public property
      public String Name
      {
      get
      {
      returnname.ToUpper();
      }
      set
      {
      name = value;
      refCount++;
      }
      }
      }
      Can hide implementation detail inside a property
      Hence “looks like a field, behaves like a method”
    • Properties: access modifiers
      class Thing
      {
      // Private field (the “backing field”)
      private String _name;
      // Public property
      public String Name
      {
      get
      {
      return _name;
      }
      private set
      {
      _name = value;
      }
      }
      }
      Now only the class itself can modify the value
      Any object can get the value
    • Properties: getter only
      class Thing
      {
      // Public property
      public intCurrentHour
      {
      get
      {
      returnDateTime.Now.Hour;
      }
      }
      }
      In this case it doesn’t make sense to offer a setter
      Can also implement a setter but no getter
      Notice that Now and Hour are both properties too (of DateTime) – and Now is static!
    • Properties: even simpler example
      class Thing
      {
      // Private field (the “backing field”)
      private String _name;
      // Public property
      public String Name
      {
      get
      {
      return _name;
      }
      set
      {
      _name = value;
      }
      }
      }
      class Thing
      {
      // If all you want is a simple
      // getter/setter pair, no need for a
      // backing field at all
      public String Name { get; set; }
      // As you might have guessed, access
      // modifiers can be used
      public boolIsBusy { get; privateset; }
      }
    • Properties
      A really core feature of C#
      You’ll see them everywhere
      DateTime.Now
      String.Length
      etc.
      Get into the habit of using a property whenever you need a getter and/or setter
      Preferred to using GetValue(), SetValue() methods
      Never use public fields!
    • Interfaces
      Very similar to interfaces in Java
      Or M-classes (mixins) in Symbian
      Like a class, but all its members are implicitly abstract
      i.e. it does not provide any method implementations, only method signatures
      A class can only inherit from a single base class, but may implement multiple interfaces
    • foreach
      Simplified for loop syntax (familiar from Qt!)
      int[] myInts = new int[] { 1, 2, 3, 4, 5 };
      foreach (intiinmyInts)
      {
      Console.WriteLine(i);
      }
      Works with built-in arrays, collection classes and any class implementing IEnumerable interface
      Stringimplements IEnumerable<char>
    • readonly
      For values that can only be assigned during construction
      class Thing
      {
      private readonlyString name;
      privatereadonlyintage =42;// OK
      public Thing() {
      name = "Fred";// Also OK
      }
      public void SomeMethod() {
      name = "Julie";// Error
      }
      }
    • readonly & const
      C# also has the const keyword
      As in C++, used for constant values known at compile time
      Not identical to C++ const though
      Not used for method parameters
      Not used for method signatures
    • Parameter modifiers: ref
      No (explicit) pointers or references in C#
      In effect, all parameters are passed by reference
      But not quite...
      static void Main(string[] args) {
      String message = "I'm hot";
      negate(message);
      Console.WriteLine(message);
      }
      static void negate(String s) {
      s += "... NOT!";
      }
      Result:
      > I'm hot
    • Parameter modifiers: ref
      Although param passing as efficient as “by reference”, effect is more like “by const reference”
      The ref keyword fixes this
      static void Main(string[] args) {
      String message = "I'm hot";
      negate(ref message);
      Console.WriteLine(message);
      }
      static void negate(refString s) {
      s += "... NOT!";
      }
      Result:
      > I'm hot... NOT!
    • Parameter modifiers: out
      Like ref but must be assigned in the method
      static void Main(string[] args) {
      DateTime now;
      if (isAfternoon(out now)) {
      Console.WriteLine("Good afternoon, it is now " + now.TimeOfDay.ToString());
      }
      else {
      Console.WriteLine("Please come back this afternoon.");
      }
      }
      static boolisAfternoon(out DateTimecurrentTime) {
      currentTime = DateTime.Now;
      returncurrentTime.Hour >= 12;
      }
    • Delegates
      Delegates are how C# defines a dynamic interface between two methods
      Same goal as function pointers in C, or signals and slots in Qt
      Delegates are type-safe
      Consist of two parts: a delegate type and a delegate instance
      I can never remember the syntax for either!
      Keep a reference book handy… 
    • Delegates
      A delegate type looks like an (abstract) method declaration, preceded with the delegate keyword
      A delegate instance creates an instance of this type, supplying it with the name of a real method to attach to
      Example on next slide
    • Delegates
      // Delegate type (looks like an abstract method)
      delegate intTransform(intnumber);
      // The real method we're going to attach to the delegate
      static intDoubleIt(intnumber) {
      return number * 2;
      }
      static void Main(string[] args) {
      // Create a delegate instance
      Transform transform;
      // Attach it to a real method
      transform = DoubleIt;
      // And now call it (via the delegate)
      intresult = transform(5);
      Console.WriteLine(result);
      }
      Result:
      > 10
    • Multicast delegates
      A delegate instance can have more than one real method attached to it
      Transform transform;
      transform += DoubleIt;
      transform += HalveIt;
      // etc.
      Now when we call transform(), all methods are called
      Called in the order in which they were added
    • Multicast delegates
      Methods can also be removed from a multicast delegate
      transform -= DoubleIt;
      You might start to see how delegates could be used to provide clean, decoupled UI event handling
      e.g. handling mouse click events
      But…
    • Multicast delegates: problems
      What happens if one object uses = instead of += when attaching its delegate method?
      All other objects’ delegate methods are detached!
      What if someone sets the delegate instance to null?
      Same problem: all delegate methods get detached
      What if someone calls the delegate directly?
      All the delegate methods are called, even though the event they’re interested in didn’t really happen
    • Events
      Events are just a special, restricted form of delegate
      Designed to prevent the problems listed on the previous slide
      Core part of C# UI event handling
      Controls have standard set of events you can attach handlers to (like signals in Qt), e.g.:
      myButton.Click += OnButtonClicked;
    • Advanced C# and .NET
      Generics
      Look and behave pretty much exactly like C++ templates
      Assemblies
      Basic unit of deployment in .NET
      Typically a single .EXE or .DLL
      Extra access modifier internal(in addition to public, protected and private) gives access to other classes within the same assembly
      Only really makes sense in a class library DLL
    • Further reading
      Reference documentation on MSDN:http://msdn.microsoft.com/en-us/library
      Microsoft’s Silverlight.net site:http://www.silverlight.net/
      StackOverflow of course!http://stackoverflow.com/
      C# in a Nutshell – highly recommended!http://oreilly.com/catalog/9780596800956/
      Free MS Press eBook: ProgrammingWindows Phone 7http://www.charlespetzold.com/phone/