Dot Net Perls

C# Cheat Sheet

by Sam Allen - Updated June 13, 2009
C# homework assignment

Problem. 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. Solution. This table contains many common tasks in C#, with columns containing the title, description, and example code.

Arrays
Create new arrayCreate 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 arrayCreate new int or string array with certain values.
int[] cat = {1, 4, 6};
string[] a = {"dog", "cat", "plant"};
Assign arraySet element in array to value.
cat[0] = 3;
cat[1] = 4;
cat[4] = 7;
Check array sizeUse array's length property, then access elements.
if (cat.Length == 3)
{
    // 3 elements
}
Sort arraySort 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 arrayUse 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 arrayUse extension 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 ListIterate 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 arrayReorder elements in array backwards.
int[] a = {5, 6, 1};
Array.Reverse(a);
// 1, 6, 5
Methods
Ref parameterAllow 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 parameterAllow 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
Split stringDivide 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 linesDeclare a string with newlines in it.
Use "" for a quote.
string s = @"line 1
line 2
line 3";
Combine stringsAdd strings together (also called concatenation).
Use overloaded + operator.
string s1 = "cat";
string s2 = "dog";
string c = s1 + " and " + s2;
// c = "cat and dog"
Compare stringsSee 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 checkSee 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 lengthFind number of characters in string.
string c = "cat";
if (c.Length == 3)
{
    // true
}
Append strings quicklyUse 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 stringUppercase each letter in string.
string s = "cat";
s = s.ToUpper();
// s = "CAT"
Uppercase first letterUppercase 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 intTake 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 stringGet part of string based on indexes.
string s = "developer";
string b = s.Substring(0, 7);
// b = "develop"
Remove whitespaceTrim whitespace at beginning and ending of string.
[C# Trim String Tips - dotnetperls.com]
string s = " cat  ";
string t = s.Trim();
// t = "cat"
Change string charactersModify 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 positionFind position of letter in string using IndexOf.
[C# IndexOf String Examples - dotnetperls.com]
string s = "word";
int i = s.IndexOf("r");
// i = 2
Classes
Declare constructorCreate new constructor for class.
class C
{
    public C(int a)
    {
        // initialize
    }
}
Cast safelyUse 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 referenceCauses exception in programs.
Null variable used.
[C# Exception Types - dotnetperls.com]
string s = null;
if (s.Length == 0)
{
    // exception raised
}
New objectCreate a new object of a kind.
class C
{
    // impl.
}
class Program
{
    void Main()
    {
        C name = new C();
    }
}
SingletonMake 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
Read file linesRead in each line of file into array.
string[] lines =
    File.ReadAllLines("file.txt");
// lines[0] = "..."
// lines[1] = "..."
Read text fileRead in entire file containing text.
[C# File Handling - dotnetperls.com]
string f =
    File.ReadAllText("file.txt");
// f = "..."
Read lines separatelyRead 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 fileAdd text to end of file on disk.
File.AppendAllText("file.txt",
    "..." + Environment.NewLine);
Write fileWrite text to file on disk, replacing any existing files.
File.WriteAllText("file.txt",
    "...");
Directory existsSee if folder exists on file system.
Add using System.IO;
if (Directory.Exists("C:\\f"))
{
    // ...
}
File existsSee if file exists on disk at path.
if (File.Exists("file.txt"))
{
    // ...
}
Hashtables
Use hashtable
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 valueGet value from hashtable/Dictionary based on key.
[C# Dictionary Lookup Overview - 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 valuesUse 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
}
Language
NamespacesPut at top of file.
Required for some examples.
using System;
using System.IO;
using System.Linq;
using System.Text;
Current timeGet current time using DateTime.
[C# DateTime Tips and Tricks - dotnetperls.com]
DateTime d = DateTime.Now;
string s = d.ToString();
// s = "8/20/2008 4:18:52 PM"
Debug messageWrite diagnostics message to console.
[C# Debug Write and Assert - dotnetperls.com]
using System.Diagnostics;
class C
{
    void Method()
    {
        Debug.WriteLine("...");
    }
}
Use constants
Enum values
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 numbersUse the for loop to loop through range of values.
for (int i = 0; i < 100; i++)
{
    // 0, 1, 2, 3, ... 99
}
Catch exceptionsDetect errors and try to recover from them.
try
{
    int i = 1 / 0;
}
catch (Exception)
{
    // log error
}
Switch statementCompare value against constant values.
Faster than if.
switch(v)
{
    case "cat":
    case "tiger":
        {
            // feline
            break;
        }
    case "dog":
    default:
        {
            // other
            break;
        }
}
Interfaces
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 interfacesUse 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.

Dot Net Perls
Language Features | DllImport and Dllexport for... | Global Variable Use | Process.Start Command-Line Examples | Timer Tutorial | WebClient Tutorial
C# | Reflection Field Example | Validate Characters in String | Main Args Examples | Enum String Method
© 2009 Sam Allen. All rights reserved.