MPL 31 C#
MPL 31 C#
Commonalities
• Compile into machine-independent, language-
independent code which runs in a managed
execution environment
• Garbage Collection coupled with the elimination
of pointers
• Powerful reflection capabilities
• No header files, all code is written inline
• Classes all descended from ‘object’ and must be
allocated on the heap with ‘new’ keyword
• Thread support (similar to Java)
Java and C# - Some
Commonalities
• Single inheritance
• Interfaces
• No global functions or constants, everything belongs
to a class
• Arrays and strings with built-in bounds checking
• The "." operator is always used (no more ->, ::
operators)
• ‘null’ and ‘boolean’/’bool’ are keywords
• All values must be initialized before use
• Only Boolean expressions are allowed in ‘if’
statements
• Try Block can have a finally clause
• Both C# and Java compile initially to an
intermediate language: C# to Microsoft
Intermediate Language (MSIL), and Java to
Java bytecode
• In each case the intermediate language can be
run by interpretation, or just-in-time compilation,
on an appropriate 'virtual machine'
• In C#, however, more support is given for the
further compilation of the intermediate language
code into native code
Some C# features
• More primitive data types than Java
• More extension to value types
• Supports safer enumeration types
• Support for ‘struct’ – light weight objects
• Operator overloading
• 'delegates' - type-safe method pointers used to
implement event-handling
• Three types of arrays:
– Single dimensional
– Multi-dimensional rectangular
– Multi-dimensional jagged
• Restricted use of pointers
• The 'switch' statements has been changed
to disallow 'fall-through' behavior
• Support for class 'properties'
C# Hello World
using System; // System namespace
foo.size = foo.size + 1;
Reference Types
• The two pre-defined reference types are object and
string
• ‘object’ is the ultimate base class of all other types
• New reference types can be defined using 'class',
'interface', and 'delegate' declarations
• Reference types actually hold the value of a memory
address occupied by the object they reference
• Aliasing
object x = new object(); after this statement
x.myValue = 10; both ‘x.myValue’ and
‘y.myValue’ equal 20
object y = x;
y.myValue = 20;
Reference Types
• No aliasing in strings – these are immutable
– The properties of these objects can't change
themselves
– So in order to change what a string variable
references, a new string object must be created
string s1 = "hello";
string s2 = s1;
s1 = “world”; //s1 points to a new string
// s2 keeps pointing to the old string