arrow left
Back to Developer Education

    Introduction to C#

    Introduction to C#

    C# is an Object-Oriented Programming language and it is portable as it can develop software for many computer systems. C# was invented in 2002 and it is one of the programming languages widely used today. <!--more--> C# is pronounced as "C-Sharp".

    Programs written in C# utilize the .NET Framework to run. .NET is a framework used to make applications and run the .NET software. It was created by Microsoft and it runs primarily on the Windows operating system. There is an open-source implementation called Mono which is cross-platform.

    Why C#?

    C# is a unique language that is friendlier and easier to understand.

    The performance of C# is exceptional in terms of speed and it uses very few resources. Many applications can be created using C#.

    Some of the applications that can be created with C# are:

    • Web applications
    • Networking applications
    • Database applications
    • Mobile application
    • Videos games
    • Service applications

    To get started, you will need an IDE (Integrated Development Environment) to write and compile code. We will be using Visual Studio as our text editor.

    Installing C#

    After you have installed Visual Studio, choose .NET desktop development, and click Modify.

    vscode

    After the installation, click Launch to get started.

    On the new window, choose Create a new project.

    newproject

    Once you have selected Create a new project, choose "Install more tools and features" then click Next.

    newproject

    Choose Console App (.NET Core) from the list and click Next.

    newproject

    Enter your preferred project name and click Create. In this case, I will name my file HelloWorld.

    newproject

    Visual Code will automatically generate some C# code for you.

    newproject

    Let's look at the code.

    We have the code that will be generated below. It's a Hello World program.

    using System;
    
    namespace HelloWorld
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
            }
        }
    }
    

    For you to run the program, press the F5 key on your keyboard. This will compile and run your code.

    A console window will open with the following output:

    Hello World!
    
    C:\Users\Username\source\repos\HelloWorld\HelloWorld\bin\Debug\netcoreapp3.0\HelloWorld.exe (process 13784) exited with code 0.
    To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
    Press any key to close this window . . .
    

    C# Syntax

    Let's look at each line of the code above that was generated by Visual Studio:

    Line 1:

    using System;
    

    In C#, it means that we can use the classes and methods available in System. It contains commonly-used types and classes. You can explore more in the C# docs.

    Line 2:

    namespace HelloWorld 
    {
        // code declarations
    }
    

    Namespaces are used in C# to separate and organize code. They are containers consisting of methods, classes, and other namespaces.

    Line 3:

    class Program 
    {
        // code declarations
    }
    

    A class is a container that contains methods and data. Since C# is object-oriented programming, creating a class is mandatory for each program. In our case, we are creating a class called Program.

    Line 4:

    static void Main(string[] args) 
    {
        // code
    }
    

    Execution of a program begins from the Main method. Every C# program must have the Main method.

    Line 5:

    Console.WriteLine("Hello World!");
    

    Console.WriteLine() is used to print out text on the console. It prints a string and it adds a new line character to the end of the string. In our case, it's used to output "Hello World!".

    We can also use Console.Write() to print a string but it does not add a new line character to the end of the string. You can learn more on Console.WriteLine() and Console.Write() here.

    Reading character(s) from the input

    Console.ReadLine() is used to read the next characters in the input system.

    Console.Read() is used to read the next character in the input system.

    Console.ReadKey() is used to obtain the next key entered by the user. It's mostly used to hold the console for the user until he presses a key.

    Comments in C#

    Comments start with two forward slashes. The compiler will ignore comments when compiling the code.

    Example

    // This is a C# program
    

    This is a single-line comment. Comments are used by programmers to explain more about the line (what the line does). This concept is very important when a group of programmers are working together as it makes your code more readable to others.

    For multiple-line comment, we use /* and ends with */ :

    Example

    /* C# is a programming language used to create Web applications and Mobile applications.
    
    It is an amazing language. */
    

    Any text between /* and */ will be ignored by the compiler.

    Note:

    • Each line in C# ends with a semi-colon(;).

    • C# follows a top to bottom order when executing the program.

    • C# is case-sensitive as it treats Uppercase and Lowercase characters differently. e.g program and Program are different things.

    Congratulations! You just wrote your first C# program.

    Now, let's write a program that adds two numbers entered by the user.

    //This is a C# program that adds two numbers
    
    using System;
    
    namespace HelloWorld
    {
        class Program
        {       
            static void Main(string[] args)
            {
                Console.WriteLine("Enter your first number: ");
                int num1= Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Enter your second number: ");
                int num2= Convert.ToInt32(Console.ReadLine());
                int sum = num1 + num2; //adds the two numbers
                Console.WriteLine("Your Sum is " + sum); //prints the sum of the two numbers 
                Console.ReadKey();
            }
        }
     }
    

    Here's how the output of the program will look like:

    Enter your first number: 2
    
    Enter your second number: 5
    
    Your Sum is 7
    

    Let's look at the new lines in our program:

    int num1= Convert.ToInt32(Console.ReadLine());
    

    It takes data from the user and allocates it to the memory location.

    int num1 means that we are creating a memory location to hold an integer (int) and naming that memory location for future reference. In our case, we have named the memory location as num1 that will hold an integer.

    When we prompt the user to enter any details using Console.Readlint(), C# takes the input as strings therefore, we have to convert the strings to numbers using the Convert.ToInt32() method above.

    Using = (assignment operator), we are assigning the value given by the user to num1.

    Just like integers, we have a data type called double which is used to store fractional numbers:

    double num1;
    

    If you'd like to learn more about the built-in types, refer to this documentation.

    Takeaways

    In this tutorial we looked at:

    • Setting up a C# development environment.

    • A sample of C# program that prints "Hello World".

    • The various methods of collecting user inputs and using them in our program (Adding two numbers).


    Peer Review Contributions by: Mohan Raj

    Published on: Dec 22, 2020
    Updated on: Jul 12, 2024
    CTA

    Start your journey with Cloudzilla

    With Cloudzilla, apps freely roam across a global cloud with unbeatable simplicity and cost efficiency