c# for c++ programmers

31
© 2007 Compass Point, Inc. 9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected] www.compass-point.net 1 C# for C++ Programmers

Upload: russellgmorley

Post on 06-Aug-2015

139 views

Category:

Software


2 download

TRANSCRIPT

Page 1: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

1

C# for C++ Programmers

Page 2: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

2

How C# Looks

Page 3: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

3

using genericCar;

namespace Toyota;{ public class Camry : Car { private static Camry camry; private Brake brake; public void main() { camry = new Camry(); camry.getBrake().ToString(); }

public Camry() { this.brake = new Brake(); }

public override Brake getBrake() { return this.brake; } }}

C# Console Application Project

Page 4: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

4

using System.IO;namespace Toyota{ public class Brake { string brakeName; public Brake() { this.brakeName = “Brake 1”; } public override string ToString() { System.Console.Out.Writeln(“I’m ” + this.brakeName); } }}

Namespace GenericCar

Class Car Public MustOverride Sub getBrake()End Class

Vb.net Class Library Project

C# Class Library Project

Page 5: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

5

Differences between C# and C++

Page 6: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

6

Pointers• Can be used in C# , but only in code blocks, methods, or classes

marked with the unsafe keyword. • Primarily used for accessing Win32 functions that use pointers.

class MyClass{

unsafe int *pX;

unsafe int MethodThatUsesPointers(){ //can use pointers}

int Method(){

unsafe{ //can use pointers}

}}

Page 7: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

7

References, Classes, and Structs

• References – are used in C#, which are effectively opaque pointers that don’t

allow the aspects of pointer functionality that can cause bugs.• Classes and structs

– are different in C#: – structs are value types, stored on the stack, and cannot inherit, – classes always reference types stored on the managed heap

and are always derivatives of System.Object.

Page 8: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

8

Accessing native code

• C# code can only access native code through PInvoke.

class PInvoke{

[DllImport("user32.dll")] public static extern int MessageBoxA( int h, string m, string c, int

type);

public static int Main() {

return MessageBoxA(0, "Hello World!", "My Message Box", 0); }

}

Page 9: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

9

Destruction

• Destruction– Same syntax as for C++, but don’t need to declare it as virtual

and shouldn’t add an access modifier.– C# cannot guarantee when a destructor will be called – called by

the garbage collector.– Can force cleanup: System.GC.Collect();– For deterministic destruction, classes should implement

IDisposable.Dispose()

– C# supports special syntax that mimics C++ classes that are instantiated on the stack where the destructor is called when it goes out of scope:

using (MyClassThatHasDestructor mc = new MyClassThatHasDestructor){

//code that uses mc} // mc.Dispose() implicitly called when leaving block.

Page 10: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

10

Miscellaneous• Binary PE format

– C# compiler will only generate managed assemblies – no native code.

• Operator Overloading– C# can overload operators, but not as many. Not commonly

used.• Preprocessor

– C# has preprocessor directives, similar to C++ but far fewer. No separate preprocessor – compiler does preprocessing.

– C# doesn’t need #include – no need to declare compiler symbols used in code but not yet defined.

Page 11: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

11

Miscellaneous

• C# doesn’t require a semicolon after a class• C# doesn’t support class objects on the stack.• const only at compile time, readonly set once at

runtime in constructor.• C# has no function pointers – delegates instead.

Page 12: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

12

C# New Features

Page 13: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

13

Delegatesdelegate void AnOperation(int x);

class AClass{

void AMethod(int i){

System.Console.WriteLine(“Number is ” + i.ToString());}

static int Main(string[] args){

AClass aClass = new AClass();AnOperation anOperation = new AnOperation(AClass.AMethod);anOperation(4);

}}

stdio console output:Number is 4

– When delegate returns a void, is a ‘multicast’ delegate and can represent more than one method. += and -= can be used to add and remove a method from a multicast delegate.

Page 14: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

14

Events• An event source EventSourceClass declares an event

with this special syntax:public delegate void EventClass(obj Sender, EventArgs e); public event EventClass SourceEvent;

• Client event handlers must look like this:void MyEventCallback(object sender, EventArgs e){

//handle event}

• Client event handlers are added to an event source like this:

EventSourceClass.SourceEvent += MyEventCallback;

• An event source then invokes the event like this:SourceEvent(this, new EventArgs());

Page 15: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

15

Attributes and Properties

• Attributes – meta info that can be accessed at runtime

[WebMethod] public ShippingPreference[] GetShippingPreferences(ShoppingCart

shoppingCart, CustomerInformation customerInformation) { }

• Propertiesclass ContainsProperty{

private int age;

public int Age{

get { return age;}set { age = value;}

}}

Page 16: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

16

Exceptions

• Exceptions in C# support a finally block:try{

//normal execution path}catch (Exception ex){

//execution jumps to here if Exception or derivative//is thrown in try block.

}finally{

//ALWAYS executes, either after try or catch clause executes.}

Page 17: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

17

Miscellaneous

• Interfaces• Threadinglock() statement (shortcut for System.Threading.Monitor)

• Boxing– Value types are primitives.– Value types can be treated as objects– Even literal types can be treated as objects.

string age = 42.ToString();

int i = 20;object o = i;

Page 18: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

18

C++ features unsupported in C#

• No templates – generics instead (C++/CLI has both)• No multiple inheritance for base classes.

Page 19: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

19

Configuration

Page 20: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

20

XML File Based

• .NET assemblies use XML-based configuration files named ExecutableName.exe.config

• Registry is not commonly used for .NET applications.

Page 21: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

21

File Format• ExecutableName.exe.config looks like:

<configuration><system.runtime.remoting>

<application><channels>

<channel ref="tcp" port="9091" /></channels>

</application></system.runtime.remoting>

<appSettings><!-- SERVICE --><!-- false will cause service to run as console application, true requires installing and running as a Windows service --><add key = "Service.isService" value = "false" /><add key = "Service.eventsourcestring" value = "CCLI Service" /><add key = "Service.servicename" value = "CCLI Service" /><add key = "ServiceAssemblyName" value = "Framework" /><add key = "ServiceClassNameConsole" value = "StarPraise.Core.ConsoleBootstrapper" /><add key = "ServiceClassNameService" value = "StarPraise.Core.ComponentController" /><add key = "Service.strStarting" value = "Service starting..." /><add key = "Service.strStopping" value = "Service Stopping..." /><!-- Configuration to use DefaultLogger - writing straight to file. Only for testing - NOT FOR PRODUCTION USE. --

><add key = "Logger.loggerAssembly" value = "Framework" /><add key = "Logger.loggerclassname" value = "StarPraise.Core.DefaultLogger" />

</configuration>

Page 22: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

22

Accessing Configuration Valuesstatic protected Logger getInstance(){

if (Logger.loggerInstance == null){

try{

ObjectHandle obj = Activator.CreateInstance(System.Configuration.ConfigurationManager.AppSettings[Logger.loggerAssembly], System.Configuration.ConfigurationManager.AppSettings[Logger.loggerclassname]);

Logger.loggerInstance = (Logger) obj.Unwrap();

Logger.loggerInstance.Start();

}catch (Exception ex){

throw new RuntimeException(ex.ToString(), new ComponentIdentity("Logger"), "getInstance");

}}

Page 23: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

23

Application Types

Page 24: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

24

Types

There are five primary application (‘executable’) projects in Visual Studio:

• Console Applications• Services• Forms Applications• Web Applications• Web Services

Page 25: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

25

Form Applications

• VS.NET creates Main and adds to the form application project.

• Windows Message Pump is encapsulated entirely within classes contained in System.Windows.

• System.Windows.Forms.Form is type automatically created by VS.NET for forms application projects.

Page 26: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

26

Forms Applicationsusing System;using System.Collections.Generic;using System.Windows.Forms;

namespace CompassPoint.ECommerce.OrderProcessingServices

{ static class Program { /// <summary> /// The main entry point for the

application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new OrderProcessingWebServiceTest());

} }}

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;

namespace CompassPoint.ECommerce.OrderProcessingServices

{ public partial class

OrderProcessingWebServiceTest : Form { public OrderProcessingWebServiceTest() { InitializeComponent(); } }}

Page 27: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

27

Web Applications• They are hosted in IIS.• A variety of compile options from compile when accessed to pre-

compile including partial compile in the creamy middle!• When webpage.aspx is accessed,

– IIS delegates to the ASP.NET runtime which • creates a runtime object model for the page, • Reads the page• Returns all markup to IIS to return to browser except • Embedded runat=server marked code in the page which it

runs in the runtime object model environment and returns the resulting markup.

Page 28: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

28

Web Services

• When a webservice.asmx is accessed, the same thing happens, but SOAP ‘method’ invocation requests are redirected to methods in the web service marked with a special attribute.

Page 29: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

29

Web Services [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class OrderProcessingService : System.Web.Services.WebService,

IOrderManager { [WebMethod] public ShippingPreference[] GetShippingPreferences(ShoppingCart

shoppingCart, CustomerInformation customerInformation) {

….

Page 30: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

30

Web Application and Service Configuration

• As for applications, configuration is stored in an XML file.

• XML file is of same format as for other types of applications.

• For both, the file is named web.config.

Page 31: C# for C++ Programmers

© 2007 Compass Point, Inc.9434 SW 55th Avenue Portland OR 97219 Phone: 503.329.1138 [email protected]

www.compass-point.net

31

Discussion