SlideShare a Scribd company logo
C# for C++ ProgrammersA crash course
C#: the basicsLots of similarities with C++Object-orientedClasses, structs, enumsFamiliar basic types: int, double, bool,…Familiar keywords: for, while, if, else,…Similar syntax: curly braces { }, dot notation,…Exceptions: try and catch
C#: the basicsActually much more similar to JavaEverything lives in a class/struct (no globals)No pointers! (so no ->, * or & notation)Garbage collection: no delete!No header filesNo multiple inheritanceInterfacesStatic members accessed with . (not ::)In a nutshell: much easier than C++ 
Hello, world!using System;// Everything's in a namespacenamespace HelloWorldApp{// A simple classclass Program    {// A simple field: note we can instantiate it on the same lineprivate static String helloMessage = "Hello, world!";// Even Main() isn't global!static void Main(string[] args)        {Console.WriteLine(helloMessage);        }    }}
C# featuresPropertiesInterfacesThe foreach keywordThe readonly keywordParameter modifiers: ref and outDelegates and eventsInstead of callbacksGenericsInstead of templates
PropertiesClass members, alongside methods and fields“field” is what C# calls a member variableProperties “look like fields, behave like methods”By convention, names are in UpperCamelCaseVery basic example on next slide
Properties: simple exampleclass Thing{// Private field (the “backing field”)private String name;// Public propertypublic String Name    {get        {            return name;        }set {// "value" is an automatic            // variable inside the settername = value;        }    }}class Program{static void Main(string[] args)    {Thing t = new Thing();        // Use the settert.Name = "Fred";        // Use the getterConsole.WriteLine(t.Name);    }}
PropertiesSo far, looks just like an over-complicated fieldSo why bother?
Properties: advanced getter/setterclass Thing{// Private field (the “backing field”)private String name;private static intrefCount = 0;// Public propertypublic String Name    {get        {            returnname.ToUpper();        }        set {name = value;refCount++;        }    }}Can hide implementation detail inside a propertyHence “looks like a field, behaves like a method”
Properties: access modifiersclass Thing{// Private field (the “backing field”)private String _name;// Public propertypublic String Name    {get        {            return _name;        }private set {_name = value;        }    }}Now only the class itself can modify the valueAny object can get the value
Properties: getter onlyclass Thing{    // Public propertypublic intCurrentHour    {get        {            returnDateTime.Now.Hour;        }    }}In this case it doesn’t make sense to offer a setterCan also implement a setter but no getterNotice that Now and Hour are both properties too (of DateTime) – and Now is static!
Properties: even simpler exampleclass Thing{// Private field (the “backing field”)private String _name;// Public propertypublic 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 allpublic String Name { get; set; }// As you might have guessed, access    // modifiers can be usedpublic boolIsBusy { get; privateset; }}
PropertiesA really core feature of C#You’ll see them everywhereDateTime.NowString.Lengthetc.Get into the habit of using a property whenever you need a getter and/or setterPreferred to using GetValue(), SetValue() methodsNever use public fields!
InterfacesVery similar to interfaces in JavaOr M-classes (mixins) in SymbianLike a class, but all its members are implicitly abstracti.e. it does not provide any method implementations, only method signaturesA class can only inherit from a single base class, but may implement multiple interfaces
foreachSimplified 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 interfaceStringimplements IEnumerable<char>
readonlyFor values that can only be assigned during constructionclass Thing{    private readonlyString name;privatereadonlyintage =42;// OKpublic Thing() {        name = "Fred";// Also OK}public void SomeMethod() {        name = "Julie";// Error}}
readonly & constC# also has the const keywordAs in C++, used for constant values known at compile timeNot identical to C++ const thoughNot used for method parametersNot used for method signatures
Parameter modifiers: refNo (explicit) pointers or references in C#In effect, all parameters are passed by referenceBut 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: refAlthough param passing as efficient as “by reference”, effect is more like “by const reference”The ref keyword fixes thisstatic 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: outLike ref but must be assigned in the methodstatic 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;}
DelegatesDelegates are how C# defines a dynamic interface between two methodsSame goal as function pointers in C, or signals and slots in QtDelegates are type-safeConsist of two parts: a delegate type and a delegate instanceI can never remember the syntax for either!Keep a reference book handy… 
DelegatesA delegate type looks like an (abstract) method declaration, preceded with the delegate keywordA delegate instance creates an instance of this type, supplying it with the name of a real method to attach toExample on next slide
Delegates// Delegate type (looks like an abstract method)delegate intTransform(intnumber);// The real method we're going to attach to the delegatestatic intDoubleIt(intnumber) {    return number * 2;}static void Main(string[] args) {// Create a delegate instanceTransform transform;    // Attach it to a real methodtransform = DoubleIt;    // And now call it (via the delegate)intresult = transform(5);Console.WriteLine(result);}Result:> 10
Multicast delegatesA delegate instance can have more than one real method attached to itTransform transform;transform += DoubleIt;transform += HalveIt;// etc.Now when we call transform(), all methods are calledCalled in the order in which they were added
Multicast delegatesMethods can also be removed from a multicast delegatetransform -= DoubleIt;You might start to see how delegates could be used to provide clean, decoupled UI event handlinge.g. handling mouse click eventsBut…
Multicast delegates: problemsWhat 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 detachedWhat if someone calls the delegate directly?All the delegate methods are called, even though the event they’re interested in didn’t really happen
EventsEvents are just a special, restricted form of delegateDesigned to prevent the problems listed on the previous slideCore part of C# UI event handlingControls have standard set of events you can attach handlers to (like signals in Qt), e.g.:myButton.Click += OnButtonClicked;
Advanced C# and .NETGenericsLook and behave pretty much exactly like C++ templatesAssembliesBasic unit of deployment in .NETTypically a single .EXE or .DLLExtra access modifier internal(in addition to public, protected and private) gives access to other classes within the same assemblyOnly really makes sense in a class library DLL
Further readingReference documentation on MSDN:http://msdn.microsoft.com/en-us/libraryMicrosoft’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/

More Related Content

PPTX
C# for C++ Programmers
PPTX
c# programmation orientée objet (Classe & Objet)
PDF
POO Java Chapitre 2 Encapsulation
PDF
POO Java Chapitre 3 Collections
PDF
Cours design pattern m youssfi partie 5 adapter
PDF
Chapter 7 - Input Output Statements in C++
PPTX
Java Queue.pptx
PPTX
Les collections en Java
C# for C++ Programmers
c# programmation orientée objet (Classe & Objet)
POO Java Chapitre 2 Encapsulation
POO Java Chapitre 3 Collections
Cours design pattern m youssfi partie 5 adapter
Chapter 7 - Input Output Statements in C++
Java Queue.pptx
Les collections en Java

What's hot (20)

PDF
Object oriented programming With C#
PDF
Chapitre5: Classes et objets
PPT
Oops concept in c#
PPTX
This pointer
PPTX
Control structures in c++
PPTX
Exception Handling in object oriented programming using C++
PPTX
Object Oriented Programming with C#
PDF
POO Java Chapitre 6 Exceptions
PPTX
Inheritance
PPTX
Program control statements in c#
PPTX
inheritance
PDF
Design pattern bridgepatern
PPSX
PDF
Cours design pattern m youssfi partie 3 decorateur
PPTX
Polymorphism in C++
PPT
Singleton design pattern
PPTX
Chap1lla génèricité.pptx
PDF
Polymorphisme
PPTX
Virtual function in C++ Pure Virtual Function
PDF
Cours design pattern m youssfi partie 7 facade bridge flyweight
Object oriented programming With C#
Chapitre5: Classes et objets
Oops concept in c#
This pointer
Control structures in c++
Exception Handling in object oriented programming using C++
Object Oriented Programming with C#
POO Java Chapitre 6 Exceptions
Inheritance
Program control statements in c#
inheritance
Design pattern bridgepatern
Cours design pattern m youssfi partie 3 decorateur
Polymorphism in C++
Singleton design pattern
Chap1lla génèricité.pptx
Polymorphisme
Virtual function in C++ Pure Virtual Function
Cours design pattern m youssfi partie 7 facade bridge flyweight
Ad

Viewers also liked (10)

PPTX
C# interview
PPTX
Abstraction in java
PPTX
Abstract class and Interface
PPT
Java Programming - Abstract Class and Interface
PPTX
Classes And Objects
PPT
C++ classes
PPTX
difference between c c++ c#
PPT
20. Object-Oriented Programming Fundamental Principles
PDF
8 abstract classes and interfaces
PPT
Chapter 9 Abstract Class
C# interview
Abstraction in java
Abstract class and Interface
Java Programming - Abstract Class and Interface
Classes And Objects
C++ classes
difference between c c++ c#
20. Object-Oriented Programming Fundamental Principles
8 abstract classes and interfaces
Chapter 9 Abstract Class
Ad

Similar to C# for C++ programmers (20)

PPS
Introduction to CSharp
PPT
Introduction to csharp
PPT
Introduction to-csharp-1229579367461426-1
PPT
Introduction to csharp
PPT
Introduction to csharp
PPT
Introduction To Csharp
PPT
Csharp4 objects and_types
PDF
1204csharp
PPT
C Language fundamentals hhhhhhhhhhhh.ppt
PPT
Constructor
PPT
Advanced c#
PPT
03 oo with-c-sharp
PPTX
CSharp presentation and software developement
PPTX
PDF
Understanding C# in .NET
PPT
Introduction to csharp
PPT
Introduction to csharp
PPT
Introduction to csharp
PPTX
CSharp Presentation
PPT
C# Language Overview Part II
Introduction to CSharp
Introduction to csharp
Introduction to-csharp-1229579367461426-1
Introduction to csharp
Introduction to csharp
Introduction To Csharp
Csharp4 objects and_types
1204csharp
C Language fundamentals hhhhhhhhhhhh.ppt
Constructor
Advanced c#
03 oo with-c-sharp
CSharp presentation and software developement
Understanding C# in .NET
Introduction to csharp
Introduction to csharp
Introduction to csharp
CSharp Presentation
C# Language Overview Part II

Recently uploaded (20)

PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Cloud computing and distributed systems.
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation theory and applications.pdf
PDF
Approach and Philosophy of On baking technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
KodekX | Application Modernization Development
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPT
Teaching material agriculture food technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
A Presentation on Artificial Intelligence
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Cloud computing and distributed systems.
Advanced methodologies resolving dimensionality complications for autism neur...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Review of recent advances in non-invasive hemoglobin estimation
Per capita expenditure prediction using model stacking based on satellite ima...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Spectral efficient network and resource selection model in 5G networks
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation theory and applications.pdf
Approach and Philosophy of On baking technology
The AUB Centre for AI in Media Proposal.docx
NewMind AI Monthly Chronicles - July 2025
KodekX | Application Modernization Development
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Teaching material agriculture food technology

C# for C++ programmers

  • 1. C# for C++ ProgrammersA crash course
  • 2. C#: the basicsLots of similarities with C++Object-orientedClasses, structs, enumsFamiliar basic types: int, double, bool,…Familiar keywords: for, while, if, else,…Similar syntax: curly braces { }, dot notation,…Exceptions: try and catch
  • 3. C#: the basicsActually much more similar to JavaEverything lives in a class/struct (no globals)No pointers! (so no ->, * or & notation)Garbage collection: no delete!No header filesNo multiple inheritanceInterfacesStatic members accessed with . (not ::)In a nutshell: much easier than C++ 
  • 4. Hello, world!using System;// Everything's in a namespacenamespace HelloWorldApp{// A simple classclass Program {// A simple field: note we can instantiate it on the same lineprivate static String helloMessage = "Hello, world!";// Even Main() isn't global!static void Main(string[] args) {Console.WriteLine(helloMessage); } }}
  • 5. C# featuresPropertiesInterfacesThe foreach keywordThe readonly keywordParameter modifiers: ref and outDelegates and eventsInstead of callbacksGenericsInstead of templates
  • 6. PropertiesClass members, alongside methods and fields“field” is what C# calls a member variableProperties “look like fields, behave like methods”By convention, names are in UpperCamelCaseVery basic example on next slide
  • 7. Properties: simple exampleclass Thing{// Private field (the “backing field”)private String name;// Public propertypublic String Name {get { return name; }set {// "value" is an automatic // variable inside the settername = value; } }}class Program{static void Main(string[] args) {Thing t = new Thing(); // Use the settert.Name = "Fred"; // Use the getterConsole.WriteLine(t.Name); }}
  • 8. PropertiesSo far, looks just like an over-complicated fieldSo why bother?
  • 9. Properties: advanced getter/setterclass Thing{// Private field (the “backing field”)private String name;private static intrefCount = 0;// Public propertypublic String Name {get { returnname.ToUpper(); } set {name = value;refCount++; } }}Can hide implementation detail inside a propertyHence “looks like a field, behaves like a method”
  • 10. Properties: access modifiersclass Thing{// Private field (the “backing field”)private String _name;// Public propertypublic String Name {get { return _name; }private set {_name = value; } }}Now only the class itself can modify the valueAny object can get the value
  • 11. Properties: getter onlyclass Thing{ // Public propertypublic intCurrentHour {get { returnDateTime.Now.Hour; } }}In this case it doesn’t make sense to offer a setterCan also implement a setter but no getterNotice that Now and Hour are both properties too (of DateTime) – and Now is static!
  • 12. Properties: even simpler exampleclass Thing{// Private field (the “backing field”)private String _name;// Public propertypublic 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 allpublic String Name { get; set; }// As you might have guessed, access // modifiers can be usedpublic boolIsBusy { get; privateset; }}
  • 13. PropertiesA really core feature of C#You’ll see them everywhereDateTime.NowString.Lengthetc.Get into the habit of using a property whenever you need a getter and/or setterPreferred to using GetValue(), SetValue() methodsNever use public fields!
  • 14. InterfacesVery similar to interfaces in JavaOr M-classes (mixins) in SymbianLike a class, but all its members are implicitly abstracti.e. it does not provide any method implementations, only method signaturesA class can only inherit from a single base class, but may implement multiple interfaces
  • 15. foreachSimplified 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 interfaceStringimplements IEnumerable<char>
  • 16. readonlyFor values that can only be assigned during constructionclass Thing{ private readonlyString name;privatereadonlyintage =42;// OKpublic Thing() { name = "Fred";// Also OK}public void SomeMethod() { name = "Julie";// Error}}
  • 17. readonly & constC# also has the const keywordAs in C++, used for constant values known at compile timeNot identical to C++ const thoughNot used for method parametersNot used for method signatures
  • 18. Parameter modifiers: refNo (explicit) pointers or references in C#In effect, all parameters are passed by referenceBut 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: refAlthough param passing as efficient as “by reference”, effect is more like “by const reference”The ref keyword fixes thisstatic 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: outLike ref but must be assigned in the methodstatic 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. DelegatesDelegates are how C# defines a dynamic interface between two methodsSame goal as function pointers in C, or signals and slots in QtDelegates are type-safeConsist of two parts: a delegate type and a delegate instanceI can never remember the syntax for either!Keep a reference book handy… 
  • 22. DelegatesA delegate type looks like an (abstract) method declaration, preceded with the delegate keywordA delegate instance creates an instance of this type, supplying it with the name of a real method to attach toExample 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 delegatestatic intDoubleIt(intnumber) { return number * 2;}static void Main(string[] args) {// Create a delegate instanceTransform transform; // Attach it to a real methodtransform = DoubleIt; // And now call it (via the delegate)intresult = transform(5);Console.WriteLine(result);}Result:> 10
  • 24. Multicast delegatesA delegate instance can have more than one real method attached to itTransform transform;transform += DoubleIt;transform += HalveIt;// etc.Now when we call transform(), all methods are calledCalled in the order in which they were added
  • 25. Multicast delegatesMethods can also be removed from a multicast delegatetransform -= DoubleIt;You might start to see how delegates could be used to provide clean, decoupled UI event handlinge.g. handling mouse click eventsBut…
  • 26. Multicast delegates: problemsWhat 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 detachedWhat 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. EventsEvents are just a special, restricted form of delegateDesigned to prevent the problems listed on the previous slideCore part of C# UI event handlingControls have standard set of events you can attach handlers to (like signals in Qt), e.g.:myButton.Click += OnButtonClicked;
  • 28. Advanced C# and .NETGenericsLook and behave pretty much exactly like C++ templatesAssembliesBasic unit of deployment in .NETTypically a single .EXE or .DLLExtra access modifier internal(in addition to public, protected and private) gives access to other classes within the same assemblyOnly really makes sense in a class library DLL
  • 29. Further readingReference documentation on MSDN:http://msdn.microsoft.com/en-us/libraryMicrosoft’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/