SlideShare uma empresa Scribd logo
1 de 29
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/

Mais conteúdo relacionado

Mais procurados

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#Sagar Pednekar
 
virtual function
virtual functionvirtual function
virtual functionVENNILAV6
 
Android kotlin coroutines
Android kotlin coroutinesAndroid kotlin coroutines
Android kotlin coroutinesBipin Vayalu
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default MethodsHaim Michael
 
Email authentication using firebase auth + flutter
Email authentication using firebase auth + flutterEmail authentication using firebase auth + flutter
Email authentication using firebase auth + flutterKaty Slemon
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)Scott Wlaschin
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Roman Elizarov
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 

Mais procurados (20)

JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Clean code
Clean codeClean code
Clean code
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
virtual function
virtual functionvirtual function
virtual function
 
Android kotlin coroutines
Android kotlin coroutinesAndroid kotlin coroutines
Android kotlin coroutines
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Email authentication using firebase auth + flutter
Email authentication using firebase auth + flutterEmail authentication using firebase auth + flutter
Email authentication using firebase auth + flutter
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Deep C
Deep CDeep C
Deep C
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 

Destaque

Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceOum Saokosal
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objectsrahulsahay19
 
difference between c c++ c#
difference between c c++ c#difference between c c++ c#
difference between c c++ c#Sireesh K
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces Tuan Ngo
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract ClassOUM SAOKOSAL
 

Destaque (10)

C# interview
C# interviewC# interview
C# interview
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
C++ classes
C++ classesC++ classes
C++ classes
 
difference between c c++ c#
difference between c c++ c#difference between c c++ c#
difference between c c++ c#
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 

Semelhante a C# for C++ programmers

CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Featurestarun308
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developersgeorgebrock
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 

Semelhante a C# for C++ programmers (20)

CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
1204csharp
1204csharp1204csharp
1204csharp
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

C# for C++ programmers

  • 1. C# for C++ Programmers A crash course
  • 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/