Presentation is loading. Please wait.

Presentation is loading. Please wait.

Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.

Similar presentations


Presentation on theme: "Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter."— Presentation transcript:

1 Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter

2 . NET Framework Class Library and Namespaces In both C++ and C#, one can develop Console and Windows applications Window apps in C++ use MFCs, in C# use the FCL for the.NET platform FCL is composed of many namespaces using System.Windows.Forms;

3 Review Every program is a class! and Main is a method Input can be in terms of strings or bytes Must be parsed to the desired type

4 Classes and Methods Building blocks of C# programs Every program is a class! (Like in Java) The Main method Each application must have exactly one

5 1 // Welcome.cs 2 // A first console program in C#. 3 4 using System; 5 6 class Welcome 7 { 8 static void Main( string[] args ) 9 { 10 Console.WriteLine( "Welcome to C# Programming!" ); 11 } 12 }

6 Getting input: Example // read second number from user as string Console.Write( "\nPlease enter the integer: " ); String sNumber = Console.ReadLine(); // convert numbers from type string to type int int number = Int32.Parse(sNumber ); int number = Int32.Parse( Console.ReadLine() ); Combining steps

7 Control Structures if, if-else, switch similar to C++ Loops similar to C++ But there is a foreach for arrays

8 Math Class Class Math is located in namespace System (unnecessary to add an assembly reference) Using methods of static classes ClassName.MethodName( argument1, arument2, … ) Example: Math.Sqrt (900.0) Constants Math.PI = 3.1415926535…

9 Type Promotion Implicit Conversion Coercion of arguments to a higher type when passed to methods or in mixed-type expressions; Explicit Conversion Done with cast or class Convert in namespace System Cast Example: int result = Square ( (int ) y );

10 Value and Reference Types Value types Contain data of the specified type Built in types (int, float, double,…) Programmer created - struct s and enumerations Reference types Contain an address Built-in (array, object and string) Programmer created – Classes, Interfaces and Delegates

11 Passing Arguments by Value vs. by Reference Value types are passed by value and reference types are passed by reference by default To pass a value type by reference so you can modify the original variable? Use the ref keyword with variables already initialized Use the out keyword when the called method will initialize it

12 Declaring Arrays int[] x; // declare reference to an array x = new int[10]; // dynamically allocate array Must use new operator to allocate dynamically the number of elements in the array

13 Array Methods and Properties Since sorting data is important in many applications,.NET Framework includes high-speed sorting capabilities // sort elements in array a Array.Sort( x ); // Determine number of elements in x by property x.Length

14 Multiple-Subscripted Arrays Rectangular arrays – syntax a little different from C++ Jagged Arrays An array of arrays of different lengths

15 // declaration of rectangular array int[,] array1 = new int[5,10]; // declaration and initialization of jagged array int [][] array2 = new int[ 3 ][]; array2[ 0 ] = new int[] { 1, 2 }; array2[ 1 ] = new int[] { 3 }; array2[ 2 ] = new int[] { 4, 5, 6 };

16 foreach Repetition Structure The foreach repetition structure is used to iterate through values in arrays No counter A variable is used to represent the value of each element foreach ( int grade in gradeArray ) { if ( grade < lowGrade ) lowGrade = grade; }

17 Initializing Class Objects: Constructors If the constructor does not explicitly initialize data members, the data members are initialized by default Primitive numeric types are set to 0 Boolean types are set to false Reference types are set to null

18 Properties Public properties allow clients to: Get (obtain the values of) private data and may control formatting and display Set (assign values to) private data and may scrutinize attempts to modify value

19 class Time { private int hour; // property Hour public int Hour { get { return hour; } set { hour = ( ( value >= 0 && value < 24 ) ? value : 0 ); } } Use it in caller as cout << time.Hour; or time.Hour = 5;

20 Garbage Collection When objects are no longer referenced, the CLR performs garbage collection Use finalizers in conjunction with the garbage collector to release resources (database connections, file access, etc.) explicitly

21 readonly Members const members are implicitly static (they are shared by all instances of the class) and must be initialized when they are declared Use keyword readonly to declare members that will be initialized in the constructor but not changed after that public readonly int radius;

22 Everyone in C#.NET community uses ToString to obtain an object’s string representation. //Method of class Point to return string representation of Point public override string ToString ( ) { return “(" + x + ", " + y + “)"; } // call method to display new point value string output += "\n\nThe new location of point is " + point; ToString

23 Other “interesting” variations from familiar C++ constructs abstract classes use keyword abstract sealed classes that cannot be overridden Interface s use inheritance notation Delegate s provide mechanism for passing method references Exception handling includes a finally block to release resources

24 Abstract Classes and Methods Must use keyword abstract in the declaration of an abstract class. Any class with an abstract method or property must be declared abstract To declare a method or property abstract, use keyword abstract in the declaration; abstract methods and properties have no implementation virtual methods do have an implementation that may be overridden.

25 sealed Classes and Methods sealed methods cannot be overridden in a derived class Methods that are declared static and private, are implicitly sealed sealed classes cannot have any derived-classes Creating sealed classes can allow some runtime optimizations e.g., virtual method calls can be transformed into non-virtual method calls

26 Creating and Using Interfaces Interfaces are defined using keyword interface Use inheritance notation to specify a class implements an interface (ClassName : InterfaceName) Classes may implement more then one interface (a comma separated list of interfaces) Classes that implement an interface must provide implementations for every method and property in the interface definition SYNTAX is differerent from C++ (and better)

27 Delegates C# does not allow passing of method references directly as arguments as in C++, but does provide delegates A Delegate is a set of references to methods Delegate objects can be passed to methods; methods can then invoke the methods the delegate objects refer to Delegates that contain one method are known as singlecast delegates and are created or derived from class Delegate Delegates that contain multiple methods are known as multicast delegates and are created or derived from class MulticastDelegate Methods that can be referred to by a delegate, must have the same signature as the delegate

28 #include using namespace std; typedef int ( * fntype) (int x); int f (int x) { return (x+1); } int g (int x) { return (x -1); } int foo ( fntype h, int z) { return (h(z)); } int main () { int a = 5; int b; b = foo (f, a); cout << b << endl; b = foo (g, a); cout << b << endl; return 0; }

29 Exception Handling Same as in C++, except may include a finally block to release resources. Exception classes have different names


Download ppt "Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter."

Similar presentations


Ads by Google