C# Cheat Sheet

by Sam Allen - Updated November 27, 2009
C# homework assignment

You need to review syntax and method names in the C# programming language. View arrays, strings, methods, sorting, and classes. Useful for homework or reference. This table contains many common tasks in the C# language, with columns containing the title, description, and example code. This is the Dot Net Perls C# Cheat Sheet.

--- Arrays section (C#) ---

Create new array
Create new array to store values.

int[] cat = new int[5];
// cat = 0, 0, 0, 0, 0

string[] s = new string[10];
// s = null, null, ...

Initialize array
Create new int or string array with certain values.

int[] cat = {1, 4, 6};
string[] a = {"dog", "cat", "plant"};

Assign array
Set element in array to value.

cat[0] = 3;
cat[1] = 4;
cat[4] = 7;

Check array size
Use array's length property, then access elements.

if (cat.Length == 3)
{
    // 3 elements
}

Sort array
Sort an array alphabetically (A - Z).
[C# Sort String Arrays - dotnetperls.com]

string[] a = new string[]
{
    "z", "a", "b"
};
Array.Sort(a);
// "a", "b", "z"

Use 2D array
Use a two-dimensional array to store a grid of values.
[C# 2D Array Use - dotnetperls.com]

int[,] i = new int[2, 2];
i[0, 0] = 0;
i[0, 1] = 1;
i[1, 0] = 2;
i[1, 1] = 3;
// 0, 1
// 2, 3

Convert List to array
Use instance method ToArray() to convert List to equivalent array.

List<int> e = new List<int>();
e.Add(1);
e.Add(2);
int[] a = e.ToArray();
// a = 1, 2

Loop through List
Iterate through each item in an array or list.

List<int> e = new List<int>();
e.Add(1);
e.Add(2);
foreach (int i in e)
{
    // 1, 2
}

Reverse array
Reorder elements in array backwards.

int[] a = {5, 6, 1};
Array.Reverse(a);
// 1, 6, 5

--- Methods section (C#) ---

Ref parameter
Allow another method to directly change value.

class C
{
    void Method()
    {
        int a = 4;
        Method2(ref a);
        // a = 5
    }
    void Method2(ref int p)
    {
        p = 5;
    }
}

Out parameter
Allow another method to directly change value.
With compile-time checking.

class C
{
    void Method()
    {
        int a;
        Method2(out a);
        // a = 5
    }
    void Method2(out int p)
    {
        p = 5;
    }
}

--- Strings section (C#) ---

Split string
Divide string into separate parts.
[C# Split String Examples - dotnetperls.com]

string c = "one,two";
string[] s = c.Split(',');
// s[0] = "one"
// s[1] = "two"

String new lines
Declare a string with newlines in it. Use "" for a quote.

string s = @"line 1
line 2
line 3";

Combine strings
Add strings together (also called concatenation).
Use overloaded + operator.

string s1 = "cat";
string s2 = "dog";
string c = s1 + " and " + s2;
// c = "cat and dog"

Compare strings
See if two strings have equal characters and lengths.

string s1 = "cat";
string s2 = "dog";
string s3 = "cat";
if (s1 == s2)
{
    // not true
}
if (s1 == s3)
{
    // success
}

Empty string check
See if string is empty or null (has no value).

string s1 = "";
string s2 = null;
string s3 = "cat";
if (string.IsNullOrEmpty(s1))
{
    // true
}
if (string.IsNullOrEmpty(s2))
{
    // true
}
if (string.IsNullOrEmpty(s3))
{
    // not true
}

Get string length
Find number of characters in string.

string c = "cat";
if (c.Length == 3)
{
    // true
}

Append strings quickly
Use StringBuilder and convert back to string.
[C# StringBuilder Secrets - dotnetperls.com]

StringBuilder b = new StringBuilder();
b.Append("Text");
b.Append(" more");
string r = b.ToString();
// r = "Text more"

Uppercase entire string
Uppercase each letter in string.

string s = "cat";
s = s.ToUpper();
// s = "CAT"

Uppercase first letter
Uppercase the first letter in string.
[C# Uppercase First Letter - dotnetperls.com]

string s = "cat";
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
string u = new string(a);
// u = "Cat"

Convert string to int
Take string containing digits and convert it to int value.
[C# int.Parse for Integer Conversion - dotnetperls.com]

string s = "105";
int i = int.Parse(s);
// i = 105

string s2 = "105.5";
double d = double.Parse(s2);
// d = 105.5

Substring of string
Get part of string based on indexes.

string s = "developer";
string b = s.Substring(0, 7);
// b = "develop"

Remove whitespace
Trim whitespace at beginning and ending of string.
[C# Trim String Tips - dotnetperls.com]

string s = " cat  ";
string t = s.Trim();
// t = "cat"

Change string characters
Modify the letters in string in-place.

string s = "cat";
char[] a = s.ToCharArray();
    // a = 'c', 'a', 't'
a[0] = 'h';
    // a = 'h', 'a', 't'
string s2 = new string(a);
    // s2 = "hat"

Letter position
Find position of letter in string using IndexOf.
[C# IndexOf String Examples - dotnetperls.com]

string s = "word";
int i = s.IndexOf("r");
// i = 2

--- Classes section (C#) ---

Declare constructor
Create new constructor for class.

class C
{
    public C(int a)
    {
        // initialize
    }
}

Cast safely
Use as operator or is operator.
Convert from one type to another.

void Method(object a)
{
    if (a is MyClass)
    {
        // correct type
    }
}
void Method2(object a)
{
    MyClass m = a as MyClass;
    if (m != null)
    {
        // correct type
    }
}

Null reference
Causes exception in programs. Null variable used.
[C# Exception Overview - dotnetperls.com]

string s = null;
if (s.Length == 0)
{
    // exception raised
}

New object
Create a new object of a kind.

class C
{
    // impl.
}
class Program
{
    void Main()
    {
        C name = new C();
    }
}

Singleton
Make a single object. One instance per AppDomain.
[C# Singleton Class - dotnetperls.com]

class S
{
    private static readonly _inst = new S();
    public static S Instance
    {
        get { return _inst; }
    }
    S()
    {
        // init
    }
}

Properties, Accessors, Getters, setters
Create properties to access fields of classes publicly.
[Visual Studio Encapsulate Field - dotnetperls.com]

class C
{
    public int P { get; set; }
}
void Method(C name)
{
    name.P = 4;
    int i = name.P;
    // i = 4
}

--- File/IO section (C#) ---

Read file lines
Read in each line of file into array.

string[] lines = File.ReadAllLines("file.txt");
// lines[0] = "..."
// lines[1] = "..."

Read text file
Read in entire file containing text.
[C# File Handling - dotnetperls.com]

string f = File.ReadAllText("file.txt");
// f = "..."

Read lines separately
Read file line-by-line with StreamReader.
Fastest and lowest memory.
[C# Using StreamReader - dotnetperls.com]

using (StreamReader s = new StreamReader("file.txt"))
{
    string t;
    while ((t = s.ReadLine()) != null)
    {
        // t = "..."
    }
}

Append to file
Add text to end of file on disk.

File.AppendAllText("file.txt", "..." + Environment.NewLine);

Write file
Write text to file on disk, replacing any existing files.

File.WriteAllText("file.txt", "...");

Directory exists
See if folder exists on file system. Add using System.IO;

if (Directory.Exists("C:\\f"))
{
    // ...
}

File exists
See if file exists on disk at path.

if (File.Exists("file.txt"))
{
    // ...
}

--- Hashtables section (C#) ---

Use Dictionary
Use the generic Dictionary object with string keys.
[C# Dictionary Examples, Keys and Values - dotnetperls.com]

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("cat", 2);
d.Add("dog", 4);
if (d.ContainsKey("cat"))
{
    // true
}
if (d.ContainsKey("hat"))
{
    // not true
}

Lookup Dictionary value
Get value from hashtable/Dictionary based on key.
[C# Dictionary Lookup Comparison - dotnetperls.com]

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("cat", 2);
if (d.ContainsKey("cat"))
{
    int v = d["cat"];
    // v = 2
}

Scan Dictionary values
Use KeyValuePair on Dictionary to list each key/value combo.
Use this style to convert to string.
[C# KeyValuePair Collection Hints - dotnetperls.com]

foreach (KeyValuePair<string, int> p in d)
{
    // p.Key, p.Value
}

Use Hashtable
Implements older version of Dictionary, slower but required sometimes.
[C# Hashtable Use, Lookups and Examples - dotnetperls.com]

Hashtable h = new Hashtable();
h.Add(400, "Blazer");

string s = h[400] as string; // Cast
if (s != null) // True
{
    Console.WriteLine(s);
}

--- Language section (C#) ---

Namespaces
Put at top of file. Required for some examples.

using System;
using System.IO;
using System.Linq;
using System.Text;

Current time
Get current time using DateTime.
[C# DateTime Examples - dotnetperls.com]

DateTime d = DateTime.Now;
string s = d.ToString();
// s = "8/20/2008 4:18:52 PM"

Debug message
Write diagnostics message to console.
[C# Debug Write Methods - dotnetperls.com]

using System.Diagnostics;
class C
{
    void Method()
    {
        Debug.WriteLine("...");
    }
}

Enums
Use enum type to assign names to numbers.
[C# Enum Tips and Examples - dotnetperls.com]

enum E
{
    None,
    Cat,
    Dog
};
void Method()
{
    E name = E.Cat;
    if (name == E.Dog)
    {
        // not true
    }
}

Loop through numbers
Use the for loop to loop through range of values.
[C# For Loops - dotnetperls.com]

for (int i = 0; i < 100; i++)
{
    // 0, 1, 2, 3, ... 99
}

Catch exceptions
Detect errors and try to recover from them.

try
{
    int i = 1 / int.Parse("0");
}
catch (Exception)
{
    // log error
}

Switch statement
Compare value against constant values. Faster than if.

switch(v)
{
    case "cat":
    case "tiger":
        {
            // feline
            break;
        }
    case "dog":
    default:
        {
            // other
            break;
        }
}

--- Interfaces section (C#) ---

Interfaces, code contracts
Define required methods for classes so they can be swapped.

public interface IName
{
    void Method();
}
class C : IName
{
    public void Method()
    {
        // ...
    }
}
class D : IName
{
    public void Method()
    {
        // ...
    }
}

Use interfaces
Use classes by their common interfaces. Improves code reuse.

void Method()
{
    C name = new C();
    Method2((IName)name);

    D name2 = new D();
    Method2((IName)name2);
}
void Method2(IName i)
{
    // ...
}

Using this page. Seach this page in your browser with "Find in page." Not optimized for printing. Other technologies are coming soon, and right now there are many more articles on the home page, with much more detail.

(Do not copy this page.)

Dot Net Perls | Search
Language | DllImport and Dllexport for DLL Interop | Global Variable Use | Process.Start Command-Line Examples | Timer Tutorial | WebClient Tutorial
C# | Parameter Optimization Tip | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen