C# Practice Questions
C# Practice Questions
1 C# Exercises
1.1 Get setup
• Download and install Mono.
• Write a Hello World program in C# (see below).
• Compile it with mcs, execute it with mono.
This enables you to play around and try the examples below.
1.2 HelloWorld.cs
using System;
class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello world!");
}
}
Compile with mcs HelloWorld.cs
Run with mono HelloWorld.exe
2. (Variables) Why do we have to define types of variables (in many programming languages)? Why is
there more than one numerical type?
3. (Operators) Make sure you understand the C# operators. They are listed here: http://msdn.microsoft.com/en-
us/library/6a71f45d.aspx – As a practise, what would the following code output?
int a = 5, b = 10, c = 5;
CuuDuongThanCong.com
Programming an experiment with Unity – Part 1 exercises – Trevor Dodds
4. (Namespaces) What is a namespace and what does the using directive do?
int b = 5;
int a = (b < 10) ? 1 : 2;
5b. Make sure you understand the use of the if statement (see above example), and switch.
6b. The same process has been implemented using a while loop. But what is wrong with the code here?
int i = 1;
while (i <= 10)
{
if ((i % 2) == 0)
continue;
Console.WriteLine("{0}", i++);
}
using System;
class Program
{
CuuDuongThanCong.com
Programming an experiment with Unity – Part 1 exercises – Trevor Dodds
int totalYears = 0;
while (balance < targetBalance)
{
balance *= interestRate;
++totalYears;
}
if (totalYears == 0)
Console.WriteLine(
"To be honest, you really didn’t need to use this calculator.");
Console.ReadKey();
}
8. (Variables) How can we convert from one variable type to another in C#?
9. (Value/reference) What’s the difference between a value type and reference type in C#? What is
boxing and unboxing?
Console.WriteLine("Testing\noutput\tusing\0escape sequences");
11. (Operators)
Some operators are difficult to tell apart, e.g. & and &&
What is the difference between the & operator and && in the following if statements?
CuuDuongThanCong.com
Programming an experiment with Unity – Part 1 exercises – Trevor Dodds
int a = 5, b = 6;
Console.WriteLine("a & b = {0}", a & b);
CuuDuongThanCong.com