1. What is C#?
C# is an object-oriented programming language from Microsoft. It lets you model real things as objects in code.
Full lesson: Csharp intro
44 questions about C# with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
C# is an object-oriented programming language from Microsoft. It lets you model real things as objects in code.
Full lesson: Csharp intro
You write a data type, then a name, then a value. The type tells the compiler what the variable can hold.
int age = 30;
string name = "Ana";
Full lesson: Csharp variables
A data type defines the kind of value a variable can store. Common types are int, double, bool, and string.
int count = 5;
double price = 9.99;
bool isReady = true;
Full lesson: Csharp data types
An if statement runs a code block when a condition is true. The condition must give a bool value.
int a = 10;
if (a < 20)
{
Console.WriteLine("a is small");
}
Full lesson: Csharp if
The else block runs when the if condition is false. Only one of the two blocks runs.
int a = 100;
if (a < 20)
{
Console.WriteLine("small");
}
else
{
Console.WriteLine("large");
}
Full lesson: Csharp if else
You write the element type, then empty brackets, then the name. You create the array with the new keyword.
int[] numbers = new int[5];
numbers[0] = 10;
Full lesson: Csharp array
The init part runs one time. Then the condition is checked and the body runs. The increment runs after each pass.
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i);
}
Full lesson: Csharp for loop
A while loop repeats a block while a condition stays true. The condition is checked before each pass.
int i = 0;
while (i < 3)
{
Console.WriteLine(i);
i++;
}
Full lesson: Csharp while loop
You use the string keyword and assign text in double quotes. The string keyword is an alias of System.String.
string first = "Rowan";
string last = "Atkinson";
string full = first + last;
Full lesson: Csharp string
A class definition starts with the class keyword and a name. The class body holds members inside curly braces.
class Box
{
public double length;
public double width;
}
Full lesson: Csharp class
An indexer lets an object use square brackets like an array. It uses get and set accessors with an index.
public string this[int index]
{
get { return names[index]; }
set { names[index] = value; }
}
Full lesson: Csharp indexer
A Hashtable stores key and value pairs. You look up a value with its key.
Hashtable table = new Hashtable();
table["one"] = 1;
Console.WriteLine(table["one"]);
Full lesson: Csharp hashtable
Use the System.IO namespace for file work. File.ReadAllText reads the whole file into a string.
using System.IO;
string text = File.ReadAllText("data.txt");
Console.WriteLine(text);
Full lesson: Csharp text files
A missing increment keeps the condition true forever. The loop then never stops. Change the loop variable inside the body.
int i = 0;
while (i < 3)
{
Console.WriteLine(i);
i++;
}
Full lesson: Csharp while loop
An array of size 5 has indexes 0 to 4. Index 5 is out of range and throws an exception.
int[] numbers = new int[5];
numbers[4] = 10;
// numbers[5] = 20; // error
Full lesson: Csharp array class
The Array class is the base class for all arrays in C#. It provides methods to create, copy, and sort arrays.
int[] nums = { 3, 1, 2 };
Array.Sort(nums);
Console.WriteLine(nums[0]); // 1
Full lesson: Csharp array class
A foreach loop repeats a block for each item in a collection. You do not need an index variable.
string[] names = { "Ann", "Bob" };
foreach (string name in names)
{
Console.WriteLine(name);
}
Full lesson: Csharp for loop
You place one if statement inside another if block. The inner if runs only when the outer condition is true.
int a = 100;
if (a == 100)
{
if (a < 200)
{
Console.WriteLine("Yes");
}
}
Full lesson: Csharp nested if
You create a BitArray with a size in bits. Each bit is false by default.
BitArray bits = new BitArray(8);
Console.WriteLine(bits.Length); // 8
Full lesson: Csharp bitarray
An interface defines a contract of methods and properties. A class that implements the interface must provide the code for all members.
interface IShape
{
double Area();
}
class Square : IShape
{
public double Side;
public double Area() { return Side * Side; }
}
Full lesson: Csharp interface
A derived class inherits members from a base class. The derived class can add new members or override base members.
class Animal { public void Eat() { Console.WriteLine("Eating"); } }
class Dog : Animal { }
Dog d = new Dog();
d.Eat();
Full lesson: Csharp inheritance
A SortedList stores key-value pairs and keeps them sorted by key. You can access items by key or by index.
SortedList sl = new SortedList();
sl.Add(2, "B");
sl.Add(1, "A");
Console.WriteLine(sl[1]); // A
Full lesson: Csharp sortedlist
You use the StreamWriter class to write text to a file. Call Write or WriteLine to add text, then Close the writer.
using (StreamWriter sw = new StreamWriter("test.txt"))
{
sw.WriteLine("Hello");
}
Full lesson: Csharp text files
A common mistake is an off-by-one error in the condition. For example, using <= instead of < can cause an extra iteration.
for (int i = 0; i <= 3; i++) // runs 4 times, not 3
{
Console.WriteLine(i);
}
Full lesson: Csharp for loop
A common mistake is using the assignment operator = instead of the equality operator ==. This assigns a value and does not compare.
int a = 5;
if (a = 10) // error: cannot convert int to bool
{
}
Full lesson: Csharp if
A common mistake is trying to change the collection inside a foreach loop. This causes an InvalidOperationException.
List<int> nums = new List<int> { 1, 2, 3 };
foreach (int n in nums)
{
nums.Add(4); // throws exception
}
Full lesson: Csharp for loop
A common mistake is adding a duplicate key. This throws an ArgumentException.
SortedList sl = new SortedList();
sl.Add(1, "A");
sl.Add(1, "B"); // throws exception
Full lesson: Csharp sortedlist
A common mistake is not implementing all interface members in the class. The compiler will report an error.
interface IShape { double Area(); }
class Square : IShape { } // error: does not implement Area
Full lesson: Csharp interface
A common mistake is trying to inherit from multiple base classes. C# does not support multiple class inheritance.
class A { }
class B { }
class C : A, B { } // error
Full lesson: Csharp inheritance
A common mistake is not closing the StreamWriter. This can lock the file and lose data.
StreamWriter sw = new StreamWriter("test.txt");
sw.WriteLine("Hello");
// missing sw.Close()
Full lesson: Csharp text files
A C# program has a namespace, a class, and a Main method. The Main method is the entry point. The program starts at Main.
using System;
class Program {
static void Main() {
Console.WriteLine("Hello");
}
}
Full lesson: Csharp basic syntax
An ArrayList is a dynamic array. It can grow and shrink at run time. It stores items as objects.
using System.Collections;
ArrayList list = new ArrayList();
list.Add(10);
list.Add("text");
Full lesson: Csharp arraylist
The Array class gives methods for all arrays. It has methods such as Sort, Reverse, and Length. These methods help you work with array data.
int[] nums = {3, 1, 2};
Array.Sort(nums);
Console.WriteLine(nums[0]);
Full lesson: Csharp array class
A do while loop runs the body first. Then it checks the condition. The body runs at least one time.
int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 3);
Full lesson: Csharp while loop
A BitArray stores bits as true or false values. You create it from a byte array or a bool array. It is useful for compact flags.
using System.Collections;
bool[] flags = {true, false, true};
BitArray bits = new BitArray(flags);
Console.WriteLine(bits[0]);
Full lesson: Csharp bitarray
A Hashtable stores key and value pairs. It uses a hash code to find each key fast. Keys must be unique.
using System.Collections;
Hashtable table = new Hashtable();
table["one"] = 1;
Console.WriteLine(table["one"]);
Full lesson: Csharp hashtable
An indexer lets an object use square brackets. You define it with the this keyword. It gives array-like access to class data.
class Box {
private int[] data = new int[5];
public int this[int i] {
get { return data[i]; }
set { data[i] = value; }
}
}
Full lesson: Csharp indexer
An interface lists method signatures with no body. A class that uses the interface must implement each method. The interface keyword starts the definition.
interface IShape {
double Area();
}
class Square : IShape {
public double Area() { return 4.0; }
}
Full lesson: Csharp interface
A derived class inherits members from a base class. You write a colon and the base class name. The derived class can add new members.
class Animal {
public void Eat() { Console.WriteLine("eat"); }
}
class Dog : Animal {
public void Bark() { Console.WriteLine("bark"); }
}
Full lesson: Csharp inheritance
A common mistake is to store mixed types and forget the cast. ArrayList stores objects, so you must cast items on read. A wrong cast causes a run-time error.
ArrayList list = new ArrayList();
list.Add(5);
int n = (int)list[0];
Full lesson: Csharp arraylist
A common mistake is to forget the update inside the loop. The condition then stays true and the loop never stops. Always change the loop variable in the body.
int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 3);
Full lesson: Csharp while loop
A common mistake is to use a missing key. A Hashtable returns null for a missing key. A null value can cause a later error.
Hashtable t = new Hashtable();
if (t.ContainsKey("one")) {
Console.WriteLine(t["one"]);
}
Full lesson: Csharp hashtable
A common mistake is to skip the bounds check. A bad index can throw an exception. Check the index before you use it.
public int this[int i] {
get {
if (i < 0 || i >= data.Length) return 0;
return data[i];
}
}
Full lesson: Csharp indexer
A common mistake is to skip the Close call. An open reader can lock the file. Use a using block to close it for you.
using (StreamReader sr = new StreamReader("a.txt")) {
string line = sr.ReadLine();
Console.WriteLine(line);
}
Full lesson: Csharp text files