C# Tutorial: Getting Started With C#

banner_C

By Huw Collingbourne for Udemy

Looking for more than a guide? Take Huw’s full C# course!

Note: This post is part of our “Getting Started” series of free text tutorials on some of our most popular course topics.

To jump to a specific section, click the table of contents below:

What Is C#?

What You need to Program C#
Your First Program – Hello World
Your Second Program – Let’s Get Visual!

The C# Language

Variables
Types
Constants
Properties
Keywords
Comments
Functions and Methods
Arguments and Parameters
Tests and Comparisons
Operators
Loops
Object Orientation
Error Handling

Putting It All Together


 

Note: Download the code of all the sample programs here.

What Is C#?

C# (‘C Sharp’) is one of the most important languages for programming on Windows. Created by Microsoft in 2000, C# is a general-purpose language with many similarities to Java. For example, just like Java, C# is object-oriented and it uses a syntax derived from the much older C language. It compiles to an intermediate code that can be run by a software program called a ‘virtual machine’. C# is a fairly ‘safe’ language that avoids many of the problems associated with C, such as memory corruption due to incorrect use of pointers to access computer memory, and memory leaks due to a failure to free up memory that is no longer needed.

Even though it was originally intended to be used exclusively for Windows programming, C# can now be used to create applications for most major operating systems, including Linux and OS X. All the tools needed for C# development are available for free. On Windows you can even get a completely free copy of Microsoft’s superb Visual Studio development environment, which is functionally almost identical to the commercial edition costing over $1,000.

What You Need to Program C#

Before you can begin programming C#, there are two essential things that you will need:

1) The .NET Framework, which includes code libraries and tools including a C# compiler.

2) A C# editor or IDE (Integrated Development Environment).
On Windows, you can install everything you need by downloading a copy of Visual Studio 2015 Community Edition. https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx
If you are programming C# on another operating system such as Linux or OS X, you will need to download the .NET-compatible Mono Framework plus an editor or IDE for your chosen platform. Suitable editors include Microsoft’s Visual Studio Code  and Xamarin Studio, both of which are free. Currently Xamarin Studio is the most fully featured C# IDE on OS X and Linux but, unlike Visual Studio 2005, it does not include an integrated GUI (Graphical User Interface) designer. You can get around this limitation either by designing user interfaces with Apple’s Xcode Interface Builder or by writing C# code to create and position components programmatically

Your First Program – Hello World

Once you have all the necessary software installed, you are ready to start programming. By long tradition, the first thing a programmer writes when learning a new language is a program that displays ‘Hello world’. This is how you would do this in Visual Studio.

Select File, New Project.
In the New Project dialog, select Visual C# in the left-hand pane.
Select Console Application in the right-hand pane.
Optionally browse to a location and a give the project a name such as ‘HelloWorld’.

csharp-newproject

The editor will now be shown and it will contain the basic C# code required to create a simple text-mode application. This includes the following block of code:

static void Main(string[] args)
{
}

This is the Main function, which defines the entry point for the application. Any code placed between the two curly brackets of this function will be run when the program loads. Let’s add some code now. Between the curly brackets, enter this:

Console.WriteLine("Hello world");

Here Console is the name of a C# class that provides functions or ‘methods’ to interact with the console – that is the ‘terminal’ or ‘system prompt’ – of your computer. WriteLine() is the name of the method that can write a line of text such as the string “Hello world”. Be sure to add the semicolon at the end of this line of code and use the same mix of upper and lowercase characters (C# is a ‘case-sensitive’ language). The Main function should now look like this:

static void Main(string[] args)
{
Console.WriteLine("Hello world");
}

To run this program, click the green ‘start button’ in the Visual Studio toolbar or press F5. This will start the compiler which converts your C# code to an intermediate format that can be run by the .NET system. When this finishes, a console window pops up and – it pops right back down again. This will probably happen too fast for you to see what, if anything, has been displayed in the console!
Let’s fix that. The Console class has many other methods and we can use one of these, ReadKey(), that will make the console wait until the user presses a key. Add this line of code to the Main function:

Console.ReadKey();

The complete code of this function should now look like this:

static void Main(string[] args)
{
Console.WriteLine("Hello world");
       Console.ReadKey();
}

Now press F5 again. This time the console pops up and shows the string “Hello world”. Now it waits for you to press a key. You can press any key on your keyboard. At that point the program ends and the console closes.

TIP: There is another way to force the console to remain visible after the program runs. Instead of pressing F5 to run the program with debugging enabled, press CTRL+F5. This runs the program without debugging and also forces the console to remain on screen when the program exits.

Your Second Program – Let’s Get Visual!

A text-based console application is all well and good. However, for most applications you will want a nice user interface with text entry fields and buttons inside a window. Visual Studio has an integrated ‘form designer’ that makes it easy to create user interfaces and attach bits of code to events such as button clicks. We’ll see how to do this in the next project, which is a simple tax calculator. Follow the steps below to get started.

Select File, New Project.
In the New Project dialog, select Visual C# in the left-hand pane.
Select Windows Forms Application in the right-hand pane.
Optionally browse to a location and a give the project a name such a ‘TaxCalc’.

This time you will see that a blank ‘form’ appears in Visual Studio. This is where you can design your application’s user interface. Before doing that, make sure that the Toolbox and the Properties windows are visible. If they aren’t, click the View menu and select Toolbox and Properties Window.

Click the Common Controls item in the Toolbox to show a set of components. Click the TextBox component then click somewhere on the blank form to drop a text box. In the same way, drop two more text boxes onto the form. Finally, select Button in the Toolbox and drop a button onto the form, right under the three text boxes. You can use the mouse to move the components around the form and drag their edges to resize them. Notice that Visual Studio has little ‘snap-to’ guidelines to help you align and centre the controls. You can also drag the edges of the form itself to change its size. By now your form should look something like this:

csharp-form

If you click the controls on your form one by one and look at the Properties panel, you will see that each control has been assigned a default name such as textBox1 and button1. It would be more useful if they had names that described their functions. Click the top text box on the form. Now find the (Name) item towards the top of the Properties panel. Click in the right-hand column and enter this text:

subtotalTB

The text box is now identified by this new name and we will be able to use that name when we get around to writing some C# code. In a similar way, click the remaining two text boxes. Name the middle one: taxTB. Name the bottom one: grandtotalTB.

Now select the button and name it: calcBtn. Even though we’ve renamed it, the button still displays the text ‘button1’. That’s because its Text property is button1. With the button still selected on the form, scroll down to Text in the Properties panel and change this to: Calculate. Notice that the text on the button changes as soon as you change this property.

Having designed the user interface, we can now make it do something by adding some C# code. My intention is that the user will be able to enter a number into the first text box (subtotalTB), then click the button in order to have a sales tax displayed in the second text field and the grand total (the subtotal plus sales tax) shown in the final text box. In order to do this, I need to add code to handle the click ‘event’ of the button.

There are many events that a control may respond to, and these are shown in the events pane, which appears when you click the little lightning bolt icon at the top of the Properties panel. You can double-click one of these events in order to create an event handler method to contain code to respond to an event. Controls may also have a default event – that is, the most common event that affects a control. To create a an event handler method for the default event, you just have to double-click the control on the form. Try double-clicking the Calculate button. Visual Studio automatically creates this method to handle a mouse click event on the button:

private void calcBtn_Click(object sender, EventArgs e)
{
}

Edit this by adding the code shown below:

private void calcBtn_Click(object sender, EventArgs e)
{
    const double TAXRATE = 0.2;     
    double subtotal = Double.Parse(subtotalTB.Text);
    double tax = subtotal * TAXRATE;
    double grandtotal = subtotal + tax;
    taxTB.Text = tax.ToString();
    grandtotalTB.Text = grandtotal.ToString();
}

To try this out, run the program and enter a value such as 100 in the first text box, then click the Calculate button. If you enter 100, the second text box will show the sales tax (calculated at 20%) – namely, 20. The last box shows the grand total; that’s the sum of the subtotal and the tax, which is 120.

csharp-calc

Let’s see how the code has calculated these values. I begin by assigning the value 0.2 (that is 20%) to the TAXRATE identifier like this:

const double TAXRATE = 0.2;

In order to access the text entered into the subtotalTB text box, I use the text box name followed by a dot, then the name Text, which (just like the Text of the button which we set using the Properties panel) is a ‘property’ of the text box.

subtotalTB.Text

This text is regarded as being of the string data type (a sequence of alphanumeric characters). Before I can use it in a calculation, I must convert it to a double (a floating point number). Double is the name of a class and Parse is one of its methods which converts a string to a floating point number. I assign the result of this conversion to the double variable subtotal:

double subtotal = Double.Parse(subtotalTB.Text);

The rest of the code simply calculates a tax value by multiplying the subtotal by the tax rate (subtotal * TAXRATE). Then it calculates the the grand total by adding the tax to the subtotal. To display the values of the tax and grandtotal variables in text boxes, I first call the ToString() method to convert the double values back to strings and assign these strings to the text box Text properties:

taxTB.Text = tax.ToString();
grandtotalTB.Text = grandtotal.ToString();

The C# Language

Even though it is very short, my tax calculator program illustrates many fundamental features of the C# language. Let’s look at some of these in more detail.

Variables

Variables are identifiers that can store values. New values can be assigned using the assignment operator ‘=’ during the execution of a program. This is how to assign the value 1.5 to a double variable called subtotal:

subtotal = 1.5;

Types

Every variable must be defined to be a certain data type before a value can be assigned to it. These are some common data types:
double a floating point number such as 10.5
int an integer such as 10
char a character between single quotes, such as ‘a’
string a sequence of characters between double quotes, such as “abc”

A variable’s type must be placed before the variable name. Optionally, a value may be assigned at the time of declaration like this:

double subtotal = 1.5;

Constants

If you want to make sure that a value cannot be changed, you should declare a constant using the keyword const, like this:

const double TAXRATE = 0.2;

By convention, constant identifiers are often written using capital letters, but this is not obligatory.

Properties

Visual controls such as buttons and text boxes come with a set of associated properties that let you get and set certain values using assignment. For example, this is how you would set the Text property of the calcBtn control to read “Click me”:

calcBtn.Text = "Click Me";

You can also create your own getter and setter properties in code. Here is a simple class called Thing that has a private variable (not visible outside the class) called _name and a public Name property (one that is accessible using dot-syntax as in the calcBtn.Text example above) to get and set the value of the _name variable:

public class Thing {
        private string _name;

        public string Name {
            get { return _name; }
            set { _name = value; }
        }
}

Keywords

Keywords are words that have a special meaning to C# and they are used to define important elements of a C# program. We’ve already seen many important keywords such as const, public, private, get, set and the names of base data types such as int and double. A full list of C# keywords can be found in Microsoft’s online C# Reference.

Comments

Comments are blocks of documentation included with your source code. They may be used to explain certain bits of code or to add other information such as a copyright notice. The C# compiler ignores comments. In C# you can create multi-line comments by placing text between the characters /* and */ like this:

/* The following method converts a string
   to a double floating-point number
   If it cannot be converted, an error
   message is displayed 
*/

You can also create single-line comments by placing text after the // characters. A single-line comment runs to the end of the current line so no comment-closing characters are required. Single-line comments are often added to the right of a line of code like this:

doubleValue = Double.Parse(aStr); // attempt to convert aStr to double

Functions and Methods

Functions are named blocks of code. A function that belongs to an object is often called a ‘method’. Methods begin with a keyword such as private to make them available only in the current scope or public to make them available more generally. Then their return type (such as string or double, or void if there is no return value) is specified, followed by the function name and a pair of parentheses. The code of the method is contained between curly brackets. If any value is returned, it must be preceded by the return keyword. This is an example of a method that returns a double value:

private double returnTen()
{
return 10.0;
}

Arguments and Parameters

Methods may take a list of ‘arguments’ – values passed to the method by other code. These arguments are represented by a comma-delimited list of named ‘parameters’. This is an example of a method that takes two double arguments and returns a double:

private double addDoubles(double num1, double num2)
{
return num1 + num2;
}

Tests and Comparisons

C# can perform tests using the if statement. The test itself must be contained within parentheses. If the test evaluates to true, the statement following the test executes. If you need multiple statements to execute, these should be enclosed by curly brackets:

if (subtotal < 1)
{
MessageBox.Show("You must enter a positive value!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}

The else keyword may optionally follow the if section. The code (either a single line or a block between curly brackets) after the else keyword will execute if the test evaluates to false. Here the tax variable is assigned subtotal * TAXRATE if the value of the subtotal variable is not less than 1:

if (subtotal < 1)
{
    MessageBox.Show("You must enter a positive value!", "Error!",
    MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{               
    tax = subtotal * TAXRATE;
}

Operators

Operators are special symbols that are used to do specific operations such as the addition and multiplication of numbers. One of the most important operators is the assignment operator = which assigns the value on its right to a variable on its left:

grandtotal = 0.0;

Note that two equals signs == test for the equality of two values.

if (subtotal == 0)
{
MessageBox.Show("You must enter a positive value!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}

These operators compare two values as explained in the comments:

==	// equals
!=	// not equals
>	// greater than
<	// less than
<=	// less than or equal to >=	// greater than or equal to

C# also has compound assignment operators. These perform a calculation prior to assigning the value to a variable on the left of the operator. Examples of compound assignment operators are shown below:

OperatorExampleNon-compound equivalent
+=a += ba = a + b
-=a -= ba = a – b
*=a *= ba = a * b
/=a /= ba = a / b

When you want to increment or decrement a value by adding 1 to or subtracting 1 from the value of a variable, you may use the ++ and — operators. Here is an example of the increment (++) operator:

int num = 100;
num++; // num is now 101

This is an example of the decrement (–) operator:

int num = 100;
num--; // num is now 99

Loops

When you want to repeat some action, you can set up a loop to keep on running a block of code either a specific number of times or while some test condition remains true. A while loop provides one common way of running code while a condition remains true. Here is a simple example:

while( x < 10 ){	// while the value of x is less than 10
	x++; 		// add 1 to the value of x
}

As with other C-like languages, C# also has for loops that can execute for a fixed number of times. Here is a simple example of a for loop:

for(int i = 1; i < 100; i++ ){
	doSomething(); 	
}

This loop declares an int variable i with the starting value of 1. At each turn through the loop, the value of i is tested and the test evaluates to true if the value of i is less than 100 (i < 100). The value of i is then incremented by 1 (i++). The loop runs 99 times (it fails when i is 100, at which point the code inside the loop is no longer run) so the method doSomething() is called 99 times.

Object Orientation

C# is an object-oriented language. What this means is that everything you work with in C# – from a string such as “Hello world” to a visual ‘form’ such as the one we designed for our tax calculator – is wrapped up inside an object that contains the data itself (for example, the characters in a string or the buttons on a form) and the methods that can be used to manipulate that data. We’ve already used several methods, such as the ToString() method of a double object to convert a floating point number to its string representation:

grandtotalTB.Text = grandtotal.ToString();

Each object that you use is created from a ‘class’. You can think of a class as a blueprint that defines the structure (the data) and the behaviour (the methods) of an object. You can write your own classes by preceding the definition with the class keyword, like this:

class MyClass {
       private string _s;

        public MyClass( ) {
            _s = "Hello world";
        }

        public string getStr( ) {
            return _s;
        }

        public void setStr( string aString ) {
            _s = aString;
        }
}

In order to create a usable object based on that class, you need to define a variable of the class type and create an object using the new keyword which calls the class constructor. A constructor has the same name as the class itself. It sets aside memory for the new object, and it may also initialize its data. This is how I create an object, ob, based on the MyClass class:

MyClass ob;
ob = new MyClass( );

Now I can call the methods from the ob object:

ob.setStr( "A new string" );
textBox1.Text = ob.getStr( );

You can also create class hierarchies in which one object descends from another and inherits all the features already defined in the ancestor class. A descendent class specifies its ancestor by placing the ancestor name after a colon in the class declaration:

public class DescendentClass : AncestorClass

Here is an example of a Treasure class which is a descendent of the Thing class. The Treasure class automatically inherits the Name and Description properties from its ancestor and it adds on its own Value property:

public class Thing {
        private string _name;

        public string Name {
            get { return _name; }
            set { _name = value; }
        }
        private string _description;

        public string Description {
            get { return _description; }
            set { _description = value; }
        }

        public Thing( string aName, string aDescription ) {
            _name = aName;
            _description = aDescription;
        }
    }

    public class Treasure : Thing {
        private double _value;

        public double Value {
            get { return _value; }
            set { _value = value; }
        }

        public Treasure( string aName, string aDescription, double aValue) 
        : base( aName, aDescription )
        {
            _value = aValue;
        }

    }

Notice that the constructor method of Treasure calls the constructor method of its ancestor (using the keyword base) in order to initialize the _name and _description variables before initializing its own _value variable:

public Treasure( string aName, string aDescription, double aValue) 
        : base( aName, aDescription )
        {
            _value = aValue;
        }

Error handling

Sometimes a program can encounter errors while it is running – due, for example, to the wrong type of data being entered by the user or read from a file. C# provides a robust exception-handling mechanism that can help you recover from this sort of error without causing your program to crash. A C# exception is an object. When an error occurs, an object of the Exception class (or one of its descendants) is created. Your code can ‘catch’ the exception object and access its properties and methods.
To catch exceptions, you need to place the code that risks causing a problem between curly brackets after the try keyword. If an error occurs, an Exception object is created and you can assign this to a named variable after the catch keyword. If an exception is caught, the code between curly brackets after the catch keyword will be executed. Here is an example which tries to convert a string variable, aStr, to a floating point number:

double doubleValue;
try
{
    	doubleValue = Double.Parse(aStr); // attempt to convert aStr to double
}
catch (Exception exc)
{
MessageBox.Show("ERROR: " + exc.Message + "\nError type: " + exc.GetType(),
"Input Error",
       MessageBoxButtons.OK, MessageBoxIcon.Error);
       doubleValue = 0.0;
}

If the string aStr has a value such as “10.5” then the conversion will succeed and no exception object will be created. But if the user has entered some invalid string such as “hello” then this clearly cannot be converted to a floating point number and an exception object will be caught and assigned to the variable exc. The exception handling code displays a message box that shows the Message property of the exception and the type returned by the exception’s GetType() method.

csharp-exception

Putting It All Together

In this brief introduction to the C# language I’ve explained how to create non-visual (console) applications as well as visual (form-based) applications using Microsoft’s Visual Studio IDE for Windows. I’ve also explained the fundamental features of the C# language including its syntax, its object-orientation and its error handling. While this describes only the basic features of C#, it should give you a good idea of how to start writing workable C# programs of your own. To end with, here is the code of a more complete version of the tax calculator that we created earlier on (you will find all this code in the downloadable code archive):

private double addDoubles(double num1, double num2)
{
    return num1 + num2;
}

/* The following method converts a string
   to a double floating-point number
   If it cannot be converted, an error
   message is displayed 
*/
private double convertToDouble( string aStr)
{
    double doubleValue;
    try
    {
        doubleValue = Double.Parse(aStr); // attempt to convert aStr to double
    }
    catch (Exception exc)
    {
        MessageBox.Show("ERROR: " + exc.Message + "\nError type: " + exc.GetType(),
                "Input Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
                doubleValue = 0.0;
            }
            return doubleValue;
}

private void calcBtn_Click(object sender, EventArgs e)
{
    const double TAXRATE = 0.2;
    double subtotal = 0.0;
    double tax = 0.0;
    double grandtotal = 0.0;
    int roundedTotal = 0;
    // make sure tax and grandtotal boxes are cleared
    taxTB.Text = "";
    grandtotalTB.Text = "";
    this.Text = "";  // set caption of window
    subtotal = convertToDouble(subtotalTB.Text);
    if (subtotal < 1)
    {
        MessageBox.Show("You must enter a positive value!", "Error!",
        MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else
    {               
        tax = subtotal * TAXRATE;
        grandtotal = addDoubles(subtotal, tax);
        taxTB.Text = tax.ToString();
        grandtotalTB.Text = grandtotal.ToString();
        roundedTotal = (int)grandtotal; // convert floating point to integer
        this.Text = roundedTotal.ToString();      
    }
}

This code illustrates many of the features of C# including types, variables and constants, methods such as convertToDouble() and addDoubles() which may receive lists of arguments between parentheses and return a value to the calling code. You will also see examples of test conditions (if..else), line and block comments and try..catch error handling. Now it’s up to you to decide what type of program you would like to write and explore the C# language in your own programming projects.