CodeGuru - C# 4.0 Cheat Sheet
CodeGuru - C# 4.0 Cheat Sheet
CodeGuru - C# 4.0 Cheat Sheet
0 Cheat Sheet
Operators
Basic (~ = bit complement) Increment/decrement Comparison Logical (^ = xor, ! = not) Assignment Conditional AND & OR Shifting Type testing Conditional ?: Null coalescing ?? (nullable type testing) Lambda + - * / %~ ++x x++ --x x-== != > >= < <= &|^! = += -= *= /= %= &= |= ^= && || >> >>= << <<= is as x == 5 ? true : false int? x = 5; int y = x + 1 ?? -1 =>
In C# 4.0, the dynamic keyword allows you work with objects whose type is only known at run-time. In certain cases, it works differently than the general object type. Operation Definitions 1: Types at runtime Working with types Definitions 2: Example dynamic d = 123; object o = 123; MessageBox.Show(d.GetType().FullName); MessageBox.Show(o.GetType().FullName); int i = d + 10; int i = (int)o + 10; private void Test(int param) { MessageBox.Show(param.ToString()); } Test(d); Test((int)o); d.MyMethod(); o.MyMethod(); d.MyMethod(); o.MyMethod(); must cast to an int compiles fails at compile-time runtime exception n/a Notes assignment to a type returns System.Int32 returns System.Int32 must cast to an int
Passing as parameters Calling methods, compiletime behaviour Calling methods, run-time behaviour
Regular Expressions
Class used Result Culture: en-US $123.45 $123.00 (not valid for floats) 00000123 1.234500e+002 1.230000e+002 123.5 123.0 123.45 123 123.45 123.00 (not valid for floats) 7b 7B Common character classes System.Text.RegularExpressions.Regex (in System.dll) string input = "ABC123"; string pattern = "[A-Z]{3}\d{3}"; Regex.IsMatch(input, pattern); // match string input = " 329A 83"; string invalid = "[^0-9]"; string safe = Regex.Replace( input, invalid, ""); // safe becomes "32983" \t Tab (\u0009) \r Carriage return (\u000D) \n New line (\u000A) \x4F ASCII character code in hex \u0020 Unicode character code in hex [aeiou] vowels [^aeiou] non-vowels [a-z] character range . period, matches any character \d decimal digits \w word characters \W non-word characters + * ? {n} {n,} {n,m} one or more occurrences zero or more occurrences zero or one occurrence exactly n occurrences at least n occurrences n to m occurrences
Formatting strings
Format string Definitions for numeric values: c or C (currency) d or D (decimal; optional precision can be given as in "d8") Example double d = 123.45; int i = 123; string.Format("{0:c}", d); string.Format("{0:c}", i)); string.Format("{0:d8}", d); string.Format("{0:d8}", i));
Floating-point types (IEEE) High-precision Real value literals (default = double; lowercase or uppercase OK) Overflow checking (default is on) Boolean Character and strings Structure Enumeration Reference types
e or E (scientific [exponential]) string.Format("{0:e}", d); string.Format("{0:e}", i)); f or F (fixed-point; optional precision can be given as in "f1") string.Format("{0:f1}", d); string.Format("{0:f1}", i));
g or G (general; optional preci- string.Format("{0:g}", d); sion can be given as in "g5") string.Format("{0:g}", i)); n or N (number) x or X (hexadecimal; x = lowercase, X = uppercase) string.Format("{0:n}", d); string.Format("{0:n}", i)); "string.Format("{0:x}", d); string.Format("{0:x}", i)); string.Format({0:X}, i));
Common quantifiers
Miscellaneous
Verbatim strings with the @ character string path = "C:\\Path\\File.txt""; string path = @"C:\Path\File.txt";
Operator Precedence
C# operators have equal precedence within a group. Operator group Primary Operator examples x.y // member access x(y) // method access x++ // post increment typeof(x) // type retrieval new X() // object creation +x -x !x ~x ++x x*y x/y x%y x+y x-y x<<y x>>y x<y x>y x is y x as y x==y x!=y x&y x^y x|y x && y x || y x ?? y x?y:z x=y x += y x *= y x => y // lambda Contextual keywords
C# 4.0 Cheat Sheet version 1.0 by Jani Jrvinen <[email protected]> Copyright Internet.com 2010.
Language Keywords
The following keywords have been defined for the C# language. An identifier can have the name of a keyword if it is prefixed with the @ sign: @readonly. Group Keywords Words abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while get set var
Unary Multiplicative Additive Shift Relational and type testing Equality Logical AND Logical XOR Logical OR Conditional AND Conditional OR Null coalescing Conditional Assignment or anonymous function
Pre-processing Directives
Declaration directives Conditional compilation directives #define symbol #undef symbol #if #else #elif #endif #line number filename #line default #line hidden #warning #error #region #endregion #pragma warning #pragma warning no(s) #pragma warning disable #pragma warning restore
Source code line directives Diagnostic directives Region directives Pragma directives
Any reference type Class T2, if T2 descends from T1 Interface I2, if T1 is not sealed and T1 does not implement I2