C# for C++ Programmers 1
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 More closely resembles 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 access with . (not ::)
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
Properties: simple example class Thing { // Private 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 = “Brutus” // Use the getter Console.WriteLine (t.Name); }
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 public String Name { get; set; } }
Properties: advanced getter/setter class Thing { // Private field private String _name; private static int refCount = 0; // Public property public String Name get return _name.ToUpper (); } set _name = value; refCounter++; Can hide implementation detail inside a property Hence “looks like a field, behaves like a method”
Properties: access modifiers class Thing { // Private 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 int CurrentHour get return DateTime.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
Interfaces Very similar to Interfaces in Java Like a class, but all its members are implicitly abstract C++ - all methods pure virtual (= 0) i.e. does not provide any method implementations, only method signatures A class can only inherit from a single base class, but may implement multiple interfaces
Limitations of Interfaces Interfaces cannot have data members They cannot define constructors or destructors Differences and similarities between an Interface and an abstract class Differences Interfaces cannot contain any implementation Interfaces cannot declare non-public members Interfaces cannot extend non-interfaces Similarities Neither can be instantiated
Syntax for declaring an Interface interface InterfaceName { refType methodName1 (param-list); // … } They are essentially abstract methods Methods declared in an interface are implicitly public; no explicit access specifier is allowed
Syntax for implementing an Interface class ClassName : InterfaceName { // Class body } When a class is implementing an interface it has to implement the entire interface A class can implement more than one interface separated by a comma A class can also inherit from a base class in combination with an interface; the name of the base class will be listed first
Simple Interface example using System; class Demo : Iabc { public static void Main (string[] args) Console.WriteLine (“Hello Interfaces”); Demo refDemo = new Demo (); refDemo.xyz (); } public void xyz () Console.WriteLine (“In Demo :: xyz”); interface Iabc void xyz (); Result: > Hello Interfaces > In Demo :: xyz
foreach Simplified for loop syntax int[] myInts = new int[] { 1, 2, 3, 4, 5 }; foreach (int i in myInts) { Console.WriteLine(i); } Works with built-in arrays, collection classes and any class implementing IEnumerable interface
readonly For values that can only be assigned during construction class Thing { private readonly string name; private readonly int age = 42; // OK; public Thing () name = “Brutus”; // Also OK } public void SomeMethod () name = “Buckeye”; // 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 = “Brutus”; MakeBuckeye(message); Console.WriteLine(message); } static void MakeBuckeye (string s) s += “Buckeye”; Result: > Brutus
Parameter modifiers: ref Although parameter passing is efficient as “by reference”, effect is more like “by const reference” The ref keyword fixes this static void Main (string[] args) { String message = “Brutus”; MakeBuckeye(ref message); Console.WriteLine(message); } static void MakeBuckeye (ref string s) s += “ Buckeye”; Result: > Brutus Buckeye
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 bool isAfternoon (out DateTime currentTime) currentTime = DateTime.Now; return currentTime.Hour >= 12;
Delegates Delegates are how C# defines a dynamic interface between two methods Same goal as function pointers in C Delegates are type-safe Consists of two parts: a delegate type and a delegate instance
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
Delegates Result: > 10 // Delegate type (looks like an abstract method) delegate int Transform(int number); static int DoubleIt (int number) { 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) int result = transform(5) Console.WriteLine(result.ToString()); 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;
Events Events are just a special, restricted form of delegate Core part of C# UI event handling Controls have standard set of events you can attach handlers to myButton.Click += OnButtonClicked;
Advanced C# and .NET Generics Assemblies Look and behave pretty much 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, private) gives access to other classes within the same assembly
?
References Whitaker, Mark. “C# for C++ Programmers” MSDN. “C for C++ Developers” Ikram, Aisha. “Quick C#”