This article will walk beginners through the steps on how to learn C#.
Contents
Note: If you are a senior developer, then this article will not help you too much. You could start with my Learn design pattern article.
Also, before you start reading the full article, I would suggest you go through this Learn C# and .NET in 4 hours video which will help you to get kick started with C# in an hour. It discusses about the necessary tools like Visual Studio, getting started with your first C# program and so on.
Just like how fish needs water to survive, C# programming is difficult without Visual Studio.
So, the first step is to get Visual Studio.
Go to https://www.visualstudio.com/ and
install this beauty. Once the installation is successful, you should see it in your program files as shown in
the below figure 1.1.
Visual Studio community edition is free for learning purposes.
Figure 1.1: Visual Studio installed
Before starting with C# labs, I would like to clear the vocabulary differences between IDE, programming language and software framework. I have seen unknowingly many developers using the word C#, .NET and Visual Studio interchangeably without knowing that they are completely different things.
Visual Studio is an IDE (Integrated Development Environment), C# and VB.NET are programming languages and .NET the framework.
.NET Framework is a huge set of reusable components or libraries. If you browse to “C:\Windows\Microsoft.NET\Framework”, you will see different versions of .NET Framework and if you browse to any of the .NET version folders, you will see files with “DLL” extensions and starting with “System
” name.
DLL stands for Dynamic link library. We will talk more about DLLs later on. But these DLLs have reusable code which does some specific task. For example, “System.Data.dll” helps to save data into RDBMS, “System.Drawing.Dll” is for display and GUI purpose and so on.
So in simple words, .NET Framework is a giant repository of reusable components.
Figure 1.2
Now, in order to build a software application, we need to write logic and invoke these components. For that, we need a programming language. C# and VB.NET are programming languages. These languages have the ability to consume and call these components.
When we talk about professional applications, the size is tremendous and for better management, we want some automation:
- Finding and referencing the .NET Framework component inside the C# code
- Help (intellisense) support for the .NET Framework components while we are coding
- C# syntax checking and compilation
- And so on
In short, we need a tool or we can say an Integrated Development Environment which can help us to organize C# code and reference .NET Framework components depending on the situation. This is all done by VS IDE (Visual Studio IDE).
If you see Visual Studio, it looks like something as shown in the below screen. Yes, it looks complex for beginners at the start, but as you start getting friendly with it, you will know how simple and useful this tool is.
Figure 1.3: IDE view
Summarizing, C# is a language and it uses the .NET Framework components for completing an application.
For development, we need to get things together, like compiling the program, referencing .NET components, syntax checking, etc. that is all done by VS IDE. So VS IDE is a tool.
Figure 1.4: IDE, Language and Framework
So let’s open Visual Studio and create a simple C# console application project by following the below steps:
- Open Visual Studio from program file
- Click on file new project
- Select Windows and then select Console Application
- Give a proper name to the project and click ok
You would see some kind of code below and explorer which displays your code files. If you see, the code files are organized in a proper structure. We have solution explorer at the top and we have projects inside the solutions and a project has the code files.
So the way project is organized is by using solutions and project. A project is a self-contained logical unit of code or we can also define them as module. For example, in a software application, we can have different modules like accounting, invoicing and so on. So you can probably have one project for invoicing, one for accounting and all this will be grouped into a solution.
The references node in the project shows which .NET Framework components are currently referred to in the project. “App.config” file has configuration information for the project. “Program.cs” file will have the actual C# code and the logic.
In order to run a software code in a machine, we need to go through a process termed as compiling. When you write code in languages like C# and Java which humans can understand, it is termed as higher level language. In order to run this code on the hardware machine, we need to convert them into machine language (binaries). The process of converting a higher level language to a machine language is termed as compiling.
To compile our current C# program, we need to click on Build and then say Build Solution as shown in the below figure.
You can see in the menu that we have a build solution and build “Lab1LearnCsharp
”. Build solution will build all projects in the solution while building “Lab1LearnCsharp
” will build that particular project.
In case you are wondering what is that build, rebuild and clean solution, please go through this video build vs rebuild vs clean solution.
If you are curious to know where are the final files of compilation, you can right click on the solution and click on “Open Folder in file explorer”.
You will see that there are two directories “bin” and “obj”. The “obj” folder has individual binary files but they are still not linked. While “bin” folder has the final compiled binaries.
So now with all the wisdom I have discussed on top, you must be thinking that “bin” is nothing but the final machine code. But that’s not entirely true. When you click on build, the .NET compiler compiles it to an intermediate language code in short we can also IL code. This IL code is a half compiled code.
In case you want to see the IL code, you can click on program file and open the developer command prompt and type ILDASM
in the command.
You should see something as shown in the below screen. ILDASM (IL Disassembler) is a simple tool which comes with Visual Studio installation and it helps to see the IL code. Click on file open and browse to the “bin” directory and try opening the “exe”.
If you open the EXE, you should see something as shown in the below figure. This is the IL code. So you can see the EXE is not a fully compiled machine binary, but a half compiled code.
The next question that comes to our mind is who does the final compilation and when does it happen? The final compilation is done during runtime and it’s done by JIT (Just In Time compiler).
So when the application EXE starts running, JIT gets kicked off and starts compiling the code as needed on the fly to machine code.
So below is how the compilation takes place:
- C# code is compiled to IL using Visual Studio. In other words, when you hit the build, it compiles to IL code and throws the compiled IL code into debug directory.
- When the EXE starts running, it kicks of the JIT engine and JIT on demand starts compiling into optimized machine code as per that environment.
But now, the next question which raises an eyebrow is why do we need to compile into intermediate code and why not fully compiled. Because if the application is doing on the fly compilation during runtime, that can hamper the application performance.
Now when we say compiling to machine code, it not only involves source code, but also what kind of operating system we have, what is the machine configuration like 32 bit 64 bit and so on. So depending on the environment, it compiles an optimized machine code.
Now if developer does full compilation in his machine, then the machine compilation is done as per developer’s machine. When we run in a different machine, this machine code is not optimized for that environment.
So it makes lot of sense that compile during runtime because during runtime, we can know what the environment configuration is and compile optimize code as per that environment.
Let us try to understand the basic console application code we have. First, all the code is in program.cs file. In that, the first bunch of code which you come across is a bunch of “using
” statements.
The using
statements are used to reference components from .NET Framework which the code uses in “program.cs” file.
using System;
using System.Collections.Generic;
using System.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
The next thing is the “static void main
”, this thing is termed as function. A function is a group of C# statements to which you can pass input and get output. If you see the “main
” function is taking an argument “args
” and returning nothing, this nothing is denoted by using “void
”.
Hold your horses for the word “static
”. We will discuss about this sometimes later. For now, in our “Main
” function, we have just displayed “Hello
”. “Console
” is a built in namespace from .NET and “WriteLine
” is the function and we are passing “Hello
” to display.
staticvoid Main(string[] args)
{
Console.WriteLine("Hello");
}
A function is housed into a class and classes are logically grouped into something called as namespaces. We will discuss about “classes” and “namespaces” when we discuss about object oriented programming in the later sections.
Below is the code of namespace, classes and functions.
namespace Lab1LearnCSharp
{
classProgram
{
staticvoid Main(string[] args)
{
Console.WriteLine("Hello");
}
}
}
So for now, the complete C# code of programs.cs looks as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab1LearnCSharp
{
classProgram
{
staticvoid Main(string[] args)
{
Console.WriteLine("Hello");
}
}
}
To run the program, hit Ctrl + F5 and you should see the below output:
- VS: Visual Studio
- IDE: Integrated Development Environment
- DLL: Dynamic Link Library
- IL: Intermediate Language
- ILDASM: Intermediate Language Disassembler
- JIT: Just In Time compiler
When C# application executes, it needs to store some temporary data in memory, this is done in things called as variables. To declare a variable in C#, the template of the syntax goes as follows:
int num=10;
You can see I have amended the previous lab using the string
variable. So the end user puts a input and that gets stored in a string
variable and later that string
variable is displayed on the console.
staticvoid Main(string[] args)
{
stringstr = Console.ReadLine().ToString();
Console.WriteLine(str);
Console.Read();
}
So below goes the line by line explanation:
Code | Explanation |
// read data from the input keyboard | The forward double slashes are for comments. Comments mean that this is not a code but some kind of text explanation of the code. Anything in // will not compile. A good code always has comments so that new developers who come in the project can understand the same. |
stringstr = Console.ReadLine().ToString(); | In this line of code, we declare a string variable “str ” and “Console.Read() ” will make the program wait for keyboard inputs. Once some data is entered using keyboard, it gets stored in “str ” variable. |
Console.WriteLine(str) | In this line of code, we display what is stored in the “str ” variable. |
Console.Read(); | You must be surprised to see one more Console.read() . This Console.Read() will make the application wait so that we can see the output. In absence of this statement, the application will quit and we will not be able to see the results. |
One of the things in programming we always need is conditional checks. This mean if this condition is satisfied, then execute some part of code or else execute something else.
So to write “IF
” condition, we put condition inside the round brackets ( “(
“ ) and the code to be executed inside curly brackets “{
“. The code which we want to execute If the condition is not satisfied is written in the “else
” part.
if (str.Length != 0)
{
}
else
{
}
The other thing we need in any programming logic is executing some code in a loop. Now the loop can be a finite loop or an infinite one. In order to execute code in a loop, we need to use the “for
” syntax as shown in the code below. “for
” takes three parameters:
- The first parameter “
int i =0
” initializes the variable. So this for loop will start from “0
”. - The second parameter is the condition till which this
for
loop should run. In this case, it will run 9 times. If you can, guess why I said 9 times and why not 10 times? - The third parameter says whether the variable will increment or decrement.
for (int i = 0; i < 10; i++)
{
}
So below is a simple C# sample code which demonstrates the use of “if
” condition and “for
” loop. In the below sample, we are reading the input from the keyboard and then displaying that inputted value 10 times.
if (str.Length != 0)
{
}
for (int i = 0; i < 10; i++)
{
}
stringstr = Console.ReadLine().ToString();
if (str.Length != 0)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(str);
}
Console.Read();
}
Below is how the output should look like:
What’s in the next tutorial?
In the next tutorial, we will discuss about for
loops, if
conditions and reading data from console. We will also look into concepts like CLR, CTS, CLS and CAS. So a big congratulations for completing Part 1. I hope you are ready for Part 2.
For Further reading do watch the below interview preparation videos and step by step video series.