100 likes | 254 Views
C# vs. C++. What's Different & What's New. An example. C# public sometype myfn { get; set; } C++ public : sometype myfn { sometype get (); void set ( sometype value); }. Major differences. C# classes can only inherit from 1 base C# structs do not allow inheritance
E N D
C# vs. C++ What's Different & What's New
An example • C# publicsometypemyfn{ get; set; } • C++ public: sometypemyfn { sometype get (); void set (sometype value); }
Major differences • C# classes can only inherit from 1 base • C# structs do not allow • inheritance • explicit default constructors • C# arrays • are objects (can use x.length) • Use indexers& foreach • Declaration syntax is different int [ ] x;
C# - 1 • No conversion to/from bool • Type long is 64 bits • Classes are passed by reference • Structs are passed by value (or use ref/out) • No fallthrough in switchstmts • New type: delegate is type-safe & secure • public delegate int x(p1, p2);
Example of "delegate" // Declare the delegate -- defines the required fn signature: delegate double MathAction(double num); class DelegateSample { // Regular method that matches signature: static double myDoubler (double input) { return input * 2; } static void Main() { // Instantiate delegate with a named method: MathActionma = myDoubler; Console.WriteLine (ma(4.5)); // Invoke the delegate // Instantiate with an anonymous method: MathActionma2 = delegate(double input) { return input * input; }; Console.WriteLine(ma2(5)); } }
C# - 2 • Must use "new" to hide inherited members • No preprocessor macros, use Globals instead • Formerly "#included" in C/C++ • Global.cs or a compiled into a Global library • References to those variables via Globals.VariableName • New keyword, finallyALWAYS executed even if errors occurred • More operators e.g.; isand typeof. • Different functionality for some logical operators.
Logical operator differences in C# • & • ALWAYS evaluates both sides • Logical bitwise AND for int's • Logical AND for BOOL • | Similar to "&" except does logical OR • ^ Similar to "&" except does logical XOR • "is" compares types for compatibility if (x is myClass1) • "typeof" determines System.Type • E.g.; System.Type type = x.GetType();
C# - 3 • "using" vs. typedefusing Project = PC.MyCompany.Project; • "extern" - used to declare a method that is implemented externally or to define an external assembly alias • "static" only usable for classes, fields, methods, properties, operators, events, and constructors
Creating a "static" variable public class Request { private static int count=5; public static int Count { get { //Do not use the "this" keyword here //as "this" refers to "THIS INSTANCE" count++; // this really increments the count return Request.count; } // Do not provide a SET method } } In "main" call it this way: Console.WriteLine(Request.Count);