C# Syntax

Course Home | What is Syntax? | Code Example(s)

As mentioned in the programming basics course, each programming language has a specific syntax. A specific way to write code so that the compiler can compile it.

Here are some code and comments to explain the basic Syntax of C#.

//This is how we import another library or class in our class.
using System;
//In this instance we are using the System library of .NET which gives us basic objects like Strings.
using NUnit.Framework;
//So in this instance, we want to use the NUnit library, specifically the framework namespace

//A name space is a way of group similair classes, sometimes inferred by the folder structure, other time by behaviour
namespace CSharpBasics.lessons
    //We need to open our class. We start with public class followed by the name of our class.
    //So in this instance our class is called A_Syntax.
    public class A_Syntax

    //We then open curly braces. This means everything inside this brace is part of the class Syntax.
        //Here we have a variable. But the syntax is as follows
        //We start with the access modifier, followed by the Type, and then the name of our variable.
        //We then have to end the line. This is so the compiler knows where the line ends, in C# we do this with a semicolon
        public String testName;

        //Here we are declaring a method. Again we start with the modifier, followed by the Type and a name.
        //The difference here is the brackets (). These tell the compiler that the following code is a method
        public void FakeTest()
        //We then open braces as we did with the Class, to inform the compiler that the code in this braces belongs to the method
            //We do some cool stuff here

            //Then we close the brace to say that is the end of our method

        //Then we close our very first brace to inform the compiler that this is the end of our class

The nice thing about using an IDE is that if you get this syntax wrong it will usually tell you. So in VS, it will make the class red and but a squiggly red line under what it believes to be the cause.

VS Syntax Errors

In this example, I’ve added a typo in ‘public’ in the variable name and I’ve removed the brace that closes the FakeTest method. There is a lot more syntax in Java, but this should be enough to get you going.

Next Lesson ➔

Richard Bradshaw's photo

Richard Bradshaw


Software Tester, speaker and trainer at Friendly Testing. BossBoss at Ministry of Testing. Whiteboard Testing creator. Striving to improve the testing craft.