C# Cheat Sheet

Cheat sheet of common C# syntax and commands.

Comments
Multi-line comments
Multi-line comments start with a /* and end with a */
*/ This
is a 
comment */
Single line comment
Single line comments start with a \
\\ This is a comment
XML Comments
XML Comments are used for documenting classes and members.
/// <summary>This is my class</summary>
public class MyClass { }
Console
Write to the console
Writes to the console window stdout.
Console.WriteLine("Hello, World!");
Files
Write to a file
Writes and appends to a file.
File.WriteAllText("supersecretfile.txt","My output test");
File.AppendAllText("supersecretfile.txt","My output test");
Loops
For loop
Standard for loop that loops from 0 to 99.
for(int i = 0; i < 100; i++)
{
   var t = i;
}
Foreach loop
Standard foreach loop that loops over an array of strings.
public void Method(string[] strings)
{
   foreach(var item in strings)
   {
      var str = item;
      continue;
   }  
}
While loop
Standard while loop
while(x < y) 
{
   x++;
}
Processes
Get Processes
Gets a list of processes and processes by name and ID.
System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process.GetProcessesByName("myProcess");
System.Diagnostics.Process.GetProcessById(1);
Start a process
Starts notepad with myText.txt as an argument.
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "notepad.exe";
startInfo.Arguments = "myText.txt";
process.StartInfo = startInfo;
process.Start();
Syntax
Access the property of a variable
Access the property of a variable
var timeZoneInfo = new TimeZoneInfo();
var variable = timeZoneInfo.DisplayName;
Assign a constant to a variable
Assigns a constant string and integer to a variable.
var myInt = 1;
var myString = "1";
Cast
Casts from one type to another
var myInt = 1;
var myLong = (long)myInt;
Create an object
Creates an object of the specified type name.
var obj = new System.Object();
Declare a method
Declares a method that takes two arguments.
namespace CodeConverter.Test.Languages.CSharp
{
   public class Class
   {
      public void Method(string argument, int integer)
      {
      }
   }
}
Indexer
Indexer
public void Method(string str)
{
  var item = str[3];
}
Array creation initializers
Initializes a variable with a new array with the specified values.
var arr = new string[] { "my", "strings" };
Common Operators
Standard boolean operators
var eq = 1 == 2;
var notEq = 1 != 2;
var or = 1 == 2 || 2 == 1;
var and = 1 == 2 && 2 == 1;
var gt = 1 > 2;
var lt = 1 < 2;
var ge = 1 >= 2;
var le = 1 <= 2;
var plus = 1 + 1;
var minus = 1 - 1;
var bor = 1 | 1;
If, Else If, Else
Standard conditional structures
if (1 == 2)
{
}
else if ("xyz" == (new Object()))
{
}
else
{
}