C# Language

Last Updated: 2001

Reserved words can be used for variable names if prefixed with @ symbol. If you prefix a non-reserved word with @ it is no different to the unreserved work (e.g. @fred==fred)

Variables names are UNICODE based, so can include foreign characters. Usual first letter, number or _ rule applies.

JIT Compilation

Note that the C# compiler generates and executable EXE containing byte code rather that a java style standalone byte code.

Its not COM

.NET components are not registered in the registry. This information is held in "manifests"

Data Types

bool double long (64-bits)
byte float sbyte (8 bits)
char (UNICODE, so 2 bytes) short (16-bits) struct
decimal int (32-bits) ushort / uint / ulong (unsigned versions of short, int & long)
 
object (reference to an object) string (reference to a UNICODE string)  

?? I think of references as being like handles. Not sure if this is technically accurate.

refVar2 = refVar copies the reference. There is still only one object. Note that string references compare by value, not object.

Converting a value type to a reference type is called BOXING and involves copying a the value type from the stack to the heap and returning a reference to the heap version. We can't use the address of the value directly as when it went out of scope the value on the stack would be lost yet we'd end up with a pointer to an undefined value. The reverse process is called UNBOXING.

In function calls, values are always passed by value, references by reference (?? testing shows this is no so for strings ??). By reference can be forced using the ref keyword.

Note the lack of a bit type (bit type in C++ was useful in strutures to say "6 bits for day, 4 for month and x for year".

Object references can be compared using the Object.ReferencesEquals(ref1, ref2) function.

Check for type and interface support using the is operator. For example: if (o is System.String or o is IStringInterface)

The as command is like a cast except it returns null rather than a cast exception is the cast is impossible. For example: IStringInterface oFred = o as IStringInterface; if (oFred = = null) Console.Writeline("Uh Oh");

The type (Class) of an object can be returned using Type.GetType("className") or typeof(className) [note the difference in quotes]. The returned result is a Type object (i.e. not just a descriptive string) and this object can be use to, for example, extract RTTI, call methods with an instance of this class, get/set methods with an instance of this class, etc.

Enumeration

public enum myEnumName {red = 1, blue = 2, green = 3}

Arrays

Arrays are 0 based

Can be created pre-populated:  int fred[] = {1,2,3,4};

Can be rectangular (where every row has the same number of elements):  int[,] fred; fred=new int[5,5];
or jagged (where each row can have a different number of elements): int[][] fred; fred = new int[4][]; fred[1] = new int[2];

C/C++ vs C#

C# doesn't support macros (but retains conditionial compilation)
C# uses references instead of pointers, thus no -> operator
C# has automatic garbage collection. However, unlike C++, you can't presume the destructor functions execute when the object is dereferenced - you have to wait for the garbage collection to kick in.
C# requires variables to be initialised before they can be referenced (although if I try this in MS C++ I get a warning). The obvious exception to this are function parameters declared with the out keyword.
C# does not have multiple inheritance of classes (multiple inheritance of interfaces is fine). You can prevent a class being inherited by declaring it with the sealed keyword
C# only allows "fall through" in switch case statements if the case contains no code, otherwise you have to use the new construct: goto case constant (e.g. goto case 32)
C++ long is 32-bits, C# long is 64-bits
Cannot define default values for parameters in C# (although you can simulate the effect by operator overloading)
No global variables of methods in C#
In C# 'if's require a result of type bool rather than int
C# supports foreach(type varName in collectionOrArray) {...}
C# case statements only support integer and string values
C# sets class members to zero (or type equivalent) automatically (presumably this is why structs cannot have parameter-less constructors)

Managed C++

Basically C++ code that runs in the CLR environment.

Using the Windows API

A two step process: Declaration and execution:

Declaration:
    [sysimport(dll='user32.dll')]
    private static extern int MessageBoxA(int hWnd, string cMessage, string cCaption, int iTypeAndButtons);

?? doesn't work!

Execution is then like any other function call:
    MessageBoxA(0, "test", "caption", 0);

Class Stuff:

Interface Stuff

Collections

Delegates

Events

Neat Things

 

Error Handling

Other Stuff:

Shorthand:

Format Strings:

Formatting strings have the general format {parameterIndex:formatCharacterXX}. Any text outside of the curly braces is included verbatim. ParameterIndex is a zero-based index for when the formatting string has to describe more than one value (for example, "You are {0:D2} years old and you have {1:C} in the bank"). FormatCharacter is one of:

Value is numeric (where shown, some codes are also valid for enumerations):

C D E F G N X
Currency
(XX=number of decimal places (defaults to control panel values))
Decimal
(XX=width, left padded with 0s)

Enums: Numeric version of enum

Exponential
(XX = precision (in number of decimal digits))
Fixed
(XX = number of decimal places)
General
(XX = precision (in number of decimal digits)

Enums: String version of enum

Number
(1,234,567.12...)
Hex
(XX=width, left padded with 0s)

Enums: Hex version of enum
             
P R          
Percent
(XX=number of decimal places after conversion)
Round-Trip
(XX = n/a)
         

Note: FormatCharacter is not case sensitive except for "X" (Hex) where the case of FormatCharacter is used to determine the case of the resulting hex string.

Value is DataTime:

d D f F g G M (or m)
Short date format
(culture specific)
Long date format
(culture specific)
Full format
(long date format + short time format, culture specific)
Full format
(long date format + long time format, culture specific)
General format
(short date + short time, culture specific)
General format
(short date + long time, culture specific)
Month/Day pattern
(e.g. MMMM dd, culture specific)
             
R (or r) s t T u U Y (or y)
RFC123 format
(e.g. ddd, dd MMM yyyy hh:mm:ss GMT)
ISO 8601 format
(i.e. yyyy-MM-dd hh:mm:ss. Format is "sortable")
Short time pattern
(e.g. HH:MM aa, culture specific)
Long time pattern
(e.g. HH:MM:SS aa, culture specific)
As per s, but using Universal Time Universal format
(dddd, MMMM dd, yyyy hh:mm:ss aa)
Year/Month pattern
(e.g. "MMMM, yyyy", culture specific)

 

FormatCharacter can also be a picture string, using the following values:

0 # . , % E+0 \char
Digit placeholder (displayed as zero if actual number smaller) Digit placeholder (not displayed if actual number smaller) Decimal point
(culture specific)
Numeric separator
(culture specific)
Percent symbol
(culture specific)
Exponential format Literals, such as \n
             
; Everything Else d f (ff, fff etc) g (gg, etc) Other date/time t (tt, etc.)
Section separator
(value is positive formatter; value is negative formatter; value is zero formatter)
Included verbatim d = day of month,
dd = " with leading zeros, ddd = abbreviated day name, dddd = full day name
fractions of a second, to varying number of d.p. period / era
?? = A.D?
h /hh hour
m / mm minute
s / ss seconds
M / MM / MMM /MMMM month
y / yy / yyy year
am/pm

z (zz, etc.)
Time Zone
             
: /          
Time Separator Date Separator          

Notes: