2. 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
3. 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++
4. 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); } } }
5. 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
6. 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
7. 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); } }
8. Properties So far, looks just like an over-complicated field So why bother?
9. 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”
10. 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
11. 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!
12. 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; } }
13. 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!
14. 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
15. 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>
16. 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 } }
17. 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
18. 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
19. 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!
20. 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; }
21. 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…
22. 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
23. 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
24. 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
25. 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…
26. 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
27. 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;
28. 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
29. 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/