C# Tutorial for Beginners

Hello there, How are things going for you?
I hope everything is fine. 😀

My name is Nick, and I'm your C# instructor. This C# tutorial is intended for those who want to start a career in the field of C# or who want to learn more about C#.

This C# tutorial was created with all of the beginners in mind who don't know the first thing about C#.

The whole C# tutorial is divided into this and some other articles. This post contains almost all the details a beginner needs to know, from printing the data on the output console to receiving the data from the user. But before we begin the tutorial, let's list all the topics covered in this post so that it's easier for you to navigate to any particular topic.

C# Fundamentals

C# is a general-purpose, high-level computer programming language that supports a variety of paradigms, including imperative, structured, functional, object-oriented, event and task-driven, and so on.

C# was influenced by prior programming languages such as C++, Java, Pascal, ML, and many others. Recently, it has influenced Kotlin, Swift, TypeScript, and many other languages. It may also have an impact on other languages that must be developed in the future.

To be honest, C# is a powerful language for developing mobile, desktop, and web applications.

Please note: C# code appears to be very similar to Java code. As a result, learning C# for Java programmers will be much simpler. Similarly, if you don't know anything about Java, you'll be able to learn it quickly after learning C#.

Popular C# Beginners' Questions?

Who designed the C# programming language?

Anders Hejisberg, a Microsoft software engineer.

Who developed the C# programming language?

Mads Torgersen, a Microsoft program manager.

When was C# first introduced?

In the year 2000.

What is/are the filename extension(s) of C#?

.cs and.csx
For example: codescracker.cs or codescracker.csx

Getting Started with C#

Now you have enough knowledge to begin coding in C#. Instead of learning everything there is to know about a language, I believe it is better to focus on its coding skills. So let's get started.

To write all of the C# code for your teaching purposes, I'll be using "Microsoft Visual Studio" as my IDE. This is the inside view of the Microsoft Visual Studio window. I'll write all of my C# programs in it.

c sharp microsoft visual studio ide

Let me now write the first C# program. The code is as follows:

using System;

namespace MyFirstProgram
{
   class MyClass
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Hello, World!");
      }
   }
}

The screenshot below shows the "Microsoft Visual Studio Debug Console" that appears after pressing the F5 button to execute the written C# program, and it displays the output produced by the C# program.

c sharp first program output

I used a red arrow to draw your attention to the output, which is "Hello, World!"

Now, let me explain how the written C# program actually works.

A namespace is a container for either classes or other namespaces. A class, on the other hand, is a container for methods. Because all C# code must be contained within a defined class, we can refer to that class as a data container. The first line of code in the above C# program is:

using System;

The keyword here is using, and the namespace is System. This line of code indicates that I will use the System namespace in the program.

Now let's look at the second line of C# code:

namespace MyFirstProgram

Using this code, I'm creating my MyFirstProgram namespace, where I'll write all of my C# code for the current C# program. Then I've added curly braces or {}, that is used to start and/or end the code block. As a result, following MyFirstProgram, I'm beginning to write a new block of code. Now comes the third or fourth (depending on whether we include the curly bracket) line of code:

class MyClass

I'm making a class called MyClass with this code. I used an open curly bracket to start another block of code to write/create. Now comes the fourth or sixth (depending on whether we include the second opening curly bracket) line of code:

static void Main(string[] args)

This line of code will be included in all C# programs. Because every C# program requires a Main() method. The Main() method is the method that begins the execution of the C# program.

I've added the keywords static and void before the Main() method. When a method is declared static, it means that no object can call it. And void is the return type, which means that no value is returned.

Another code snippet can be found within the Main() method: String[] args, which represents an array of a sequence of strings passed to the method Main(). This occurs when the program is run. This will be important when we pass parameters to the Main() function during program execution.

Now, ignoring the curly braces, the final line of code is:

Console.WriteLine("Hello, World!");

In which Console is the System namespace class, and WriteLine() is the method that writes the string written inside it to the output. You can also remove the first line of code from the preceding C# program and write System. before Console.WriteLine() as follows, to get the same output.

System.Console.WriteLine("Hello, World!");

However, I can also use Microsoft Visual Studio IDE to write the WriteLine() method directly to produce the same output. The code is as follows:

Console.WriteLine("Hello, World!");

C# is a Case-Sensitive Language

C# is a case-sensitive language. Therefore codescracker, CodesCracker, and Codescracker are all three different variables in C#.

C# Write() Vs. WriteLine()

To perform a similar task, the Write() method can be used instead of WriteLine(). WriteLine() appends a newline to the output console window, while Write() does not. For example:

Console.WriteLine("codescracker.com");
Console.WriteLine("codescracker.com");
Console.WriteLine("codescracker.com");

produce:

codescracker.com
codescracker.com
codescracker.com

Whereas:

Console.Write("codescracker.com");
Console.Write("codescracker.com");
Console.Write("codescracker.com");

produce:

codescracker.comcodescracker.comcodescracker.com

Comments in C#

In C#, comments are used to explain or halt the execution of a block or line of code. In a C# program, comments are never executed as code. When debugging code, programmers may use comments.

A comment spans only one line and starts with //. On the other hand, comments span multiple lines and begin with /* and end with */. For example,

// Following code will print 'Hello' on output
Console.WriteLine("Hello");

int x = 10;
int y = 20;
int sum = x + y;

/* The line of code given below
 * will print the summation of 
 * 'x' and 'y' on the
 * output console */
Console.WriteLine(sum);

// Console.WriteLine("codescracker.com");

// The previous line of code, will not be executed

The output produced by this C# program demonstrating comments should exactly be

Hello
30

Variables in C#

In a previous C# program, I used three variables: x, y, and sum. Variables in C# are values or data containers. That is, whatever the value assigned to a variable, that variable represents that assigned value. Therefore, wherever we write or place the variable in the program, it represents the value assigned to it or the current value it holds. For example:

int num = 10;
string website = "codescracker.com";
string temp = website;

Console.WriteLine(num);
Console.WriteLine(website);
Console.WriteLine(temp);

The output produced by the above C# example created to demonstrate C# variables should exactly be:

10
codescracker.com
codescracker.com

In the previous example, num, website, and temp are the names of variables. where int and string are its data types. We will discuss data types in C# just after this section, but before we get to data types, let's first understand the rules that can be used to name a variable in C#.

The very simple rules we need to keep in mind while naming a variable in C# are:
A variable can be a combination of letters, digits, and underscore characters, but it must start with a letter. For example: mynum, my_num, myNum, mYNUM, my23num, mynum23_, and m23my4m3. Since C# is a case-sensitive language, therefore the variable mynum is not equal to myNum.

Please keep in mind that the const keyword can be used to keep the value of a variable constant throughout the program. That is, a variable declared with the const keyword cannot be changed, making it a read-only variable. For example:

const double pi = 3.14159265;
double rad = 18.34;
double area;
area = pi * rad * rad;

Console.WriteLine("Area of Circle = {0}", area);

The output produced by this C# example should be

Area of Circle = 1056.69228074634

In the above C# example, the {0} basically represents the value of area. It is used to print formatted strings on the output console.

Data Types in C#

Data types in C# are equally important to C# variables, as while declaring a variable, we need to define its data type to define what type of values the variable can hold.

For example, if a variable, say myVar, is used to hold small values, then there is no need to define the variable as of the long type, whose size is 8 bytes. The table given below shows the keyword used to define the type of variable along with its size and a brief description:

Keyword Size Brief Info
bool 1 bit used to define boolean type variables with either true or false values
char 2 bytes used to create variables that can contain characters
string 2 bytes per character used to define variables with multiple characters
int 4 bytes The range is from -2,147,483,648 to 2,147,483,647 and is used to define variables that can hold integer type values.
float 4 bytes used to define variables that can store floating-point values with up to seven decimal digits
long 8 bytes Variables with integer type values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
double 8 bytes used to define variables capable of storing floating-point values with 15 decimal digits

Please note: 1 byte is equal to 8 bits.

Please note: While defining variables of the float and double types, we need to end its values with F and D in this way:

float myNumOne = 12.34F;
double myNumTwo = 43.546D;

Now let me create an example demonstrating the use of variables with different data types in the same program.

bool myBool = true;
char myChar = 'x';
string myStr = "C# programming is Fun!";
int myNum = 10;
float myPerc = 85.67F;
long myContact = 1234567890;
double myArea = 32.43530D;

Console.WriteLine(myBool);
Console.WriteLine(myChar);
Console.WriteLine(myStr);
Console.WriteLine(myNum);
Console.WriteLine(myPerc);
Console.WriteLine(myContact);
Console.WriteLine(myArea);

The output of the above C# example demonstrating the data types should exactly be:

True
x
C# programming is Fun!
10
85.67
1234567890
32.4353

Please note: If you want to initialize a value or variable whose type size is greater than the variable to which the value or variable's value will be initialized, you must first typecast the value or variable. For example:

int myNum = (int) 23.43F;
Console.WriteLine(myNum);

double x = 324.54642D;
int a = (int)x;
Console.WriteLine(a);

The output of this C# example demonstrating typecasting should exactly be:

23
324

This type of casting is known as "explicit casting." There is another type of casting, whose name is implicit casting, that is done smoothly by the C# itself or automatically. In implicit casting, the smaller type automatically converts into the larger type when we initialize a value or variable of a smaller size with a variable of a larger size.

Receive Input from User in C#

In this section, I will show you how to receive input from the user at run-time of the program. You remember the method WriteLine(), right?
which is used to write the data on the output console. There is a similar method named ReadLine(), which is used to read the line entered by the user at run-time of the program. For example:

Console.WriteLine("Type anything and press ENTER key: ");
string mytext = Console.ReadLine();

Console.WriteLine("You entered: " + mytext);

If you execute this C# example, here is the output, which you'll see:

receive user input in c sharp initial output

Now if you type and press the ENTER key, the entered text will be stored in the variable named mytext, and its value will be printed back on the output console using Console.WriteLine() method. For example, in my case, let me type "C# Programming is Fun!" and press the ENTER key. The snapshot given below was taken of the output console after executing the same program with the same input as I said right now.

c sharp user input example

Please note: since the ReadLine() method treats user input as a string type. Therefore, to receive integer input, we need to do the conversion using Convert.toMethodName(). For example, to receive integer input, we need to use Convert.toInt32(), as shown in the example given below.

Console.WriteLine("Enter the First Number: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Second Number: ");
int b = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("\nSum = {0}", a+b);

The snapshot given below shows the sample run of this C# example demonstrating the receiving of a number from the user at run-time of the program.

c sharp receive integer input from user example

These are the methods used to convert from string to a particular or required type: Convert.ToBoolean(), Convert.ToDouble(), Convert.ToInt32(), and Convert.ToInt64(). Convert.ToInt32() is used for int, whereas Convert.ToInt64() is used for long data types.

Now follow the "Next Tutorial" button right after this paragraph to continue the C# tutorial. Since the content is becoming a little lengthy, I decided to split some of the remaining content into separate articles.

C# Online Quiz


« CodesCracker.com Next Tutorial »


Liked this post? Share it!