C# for C++ programmers


Published on

Published in: Technology, Business

C# for C++ programmers

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