C# Basics Best Tutorials

C# for Absolute Beginners: The Basics

C# for Absolute Beginners: Master the Basics

Master C# Basics on your way to becoming an ace C#. The objective of this article and YouTube videos is to familiarize you with the C# programming basics. This article is for absolute beginners who want to learn C# fundamentals by coding.

Table of Contents
Watch Now C# for Absolute Beginners tutorial has related videos created by the Codebuns. Watch it together with the written material for Step-By-Step explanation with CODE examples. This will reduce your learning curve and deepen your understanding where you’re uncertain.

C# Online Editors

There are many C# online editors out there, you can use for coding but I have selected 2 for this article. I have used both the editors very extensively for preparing this step-by-step C# tutorial and it worked very well for me. By the way, all the editors are lightweight and free to use in the browser.

I don’t know about you guys. But I want few basic things in the online C# editor.

First, it should have a Simple and Clean Interface. I don’t want to see lots of ads popping up all over the page. Moreover, it must have an easy-to-use interface.

Additionally, I want Code Completion in the editor; I need auto-completion with better IntelliSense support, which can provide smart completion based on variable types, function definitions, etc.

Lastly, I want Syntax Highlighting to improve code readability.

C# Online Editors


C# Variables

Variable” is the name given to a computer memory location for storing data that can be reused throughout the program; variables are used to store, retrieve, and modify changeable data.

A variable is always defined with a datatype, which means that it will hold the value of a specific type, such as string, int, float, and so on. Always assign value to a variable before using it to avoid a compile-time error.

Variable Naming Conventions in C#

You should follow these rules regarding variable names.

  • camelCase for local variables, such as name, firstName, lastName, and isMarried.
  • Can contain the letters a–z and A–Z, the numbers 0–9, and the underscore (_) character—other symbols are not allowed.
  • No spaces and cannot start with a number.
  • Cannot use C# language-keywords such as namespace, class, using, and so on.

Declaring Variables in C#

To declare a variable, use the type and then a name:

string name;
int age;

Run Demo

Type must be one of the valid data types, and variableName is the identifier. This is an explicitly typed local variable where the type is explicitly defined.

You can declare multiple variables on one line in the form of a comma-separated “,” list if they are of the same type. Use semicolon (;) if they are of different types.

string name; int age, weight;

To initialize the variable with a value, you have to use the assignment operator “=“. The variable name is on the left side of the operator and on the right side is the value, like this:

name = "Pirzada";
age = 35;

Run Demo

Alternatively, you can declare the variable with a type, and assign it a value at the same time on the same line, which is more convenient:

string name = "Pirzada";
int age = 35;

Run Demo

var Variable in C# (Type Inference)

To declare implicitly typed local variable, use the var keyword:

var name = "Pirzada";
var age = 35;

Run Demo

Now you can declare a variable without giving an explicit or real type. The var keyword in c# instructs the compiler to infer the type of a variable from the expression on the right side of the initialization statement. Actually, compiler determines and assigns the most appropriate type.

Note: var can only be declared and initialized in a single statement. Otherwise, the compiler doesn’t have anything from which to infer the type.


C# Comments

C# comments are only for you to read, not for the computer to execute. Use comments only to clarify code that’s difficult to understand.

Single-Line Comments

You can make any line into a C# single-line comment by starting it with the two forward slash marks //, indicating that the remainder of the line is a comment.

Once the compiler reads the slashes, it ignores all characters until the end of the current line.

// This is a comment
Console.WriteLine("This is not a comment");

If you run these two lines, you’ll get the following output: This is not a comment.

Run Demo

End-Of-Line Comments

You can put a comment at the end of a line, like this:

int variableName = 1; //this is a comment

Everything before // is a normal line of code, and everything after that is a comment.

Run Demo

Multi-Line Comments (Delimited comments)

C# multiline comment begins with an open comment mark /* and ends with a closed comment mark */. All the text between the delimiters is ignored by the compiler. Here is the example.

/*
Comment Line 1
Comment Line 2
*/

Run Demo


C# if-else Statement

C# if else statement is one of the most commonly used control flow statement. With if statements, you can tell the computer to make a choice by evaluating a Boolean logical expression (true or false) called condition. It allows you to tell the computer whether to run the code inside the block based on the condition or set of conditions.

if Statement

When you only need to execute code for a true condition, use an if statement.

if Condition flowchart

C#'s if condition flowchart

if Condition Example

C# if condition example

Run Demo

The value of the number variable is 8. So, the expression (number > 7) is evaluated to true because 8 is greater than 7. Hence, the statements inside the body of the if block are executed. If you change the value of the number variable from 8 to 6, then the expression will return false, which will ignore the execution of the if body.

else Statement

You can also have an else clause. Whenever the Boolean condition of the if statement is false, the else clause executes as shown in the following code block.

if else flowchart

C#'s if-else flowchart

if else Condition Example

C#'s if-else condition example

Run Demo

The value of a number variable is 6. So, the expression (number > 7) is evaluated to false because 6 is less than 7. Hence, the code inside else block is executed.

else-if Statement

C# if statement can be extended by any number of else if clauses. This statement follows directly after the if statement to let you use multiple conditions for testing.

if else-if else flowchart

C#'s if else-if else Condition Example

Note: Order of tests is important if you are using an if else-if construct.

if else-if else Condition Example

C#'s if else-if else condition example

Run Demo

In the above example, the expression (gender == “Female”) is evaluated to true, which is the condition of the else if block and everything inside the pair of braces ({ }) is carried out and the rest of if statement will be skipped.

Note: Each additional condition will only be evaluated if all previous conditions are false.


C# Conditional Operator

C# provides a conditional operator?:“, which is sometimes called C# ternary or question operator. This operator is a shorthand method of writing a simple single line if else statement (if-else shorthand).

C# Ternary operator

ternary operator

C# Ternary operator flow diagram

C#'s ternary operator flowchart

C# conditional operator uses three operands on one line. The first operand is a Boolean expression that evaluates to true or false. If the expression is true, the value of the second operand is returned; otherwise, the value of the third is returned.

bool loggedIn = true;
string status = loggedIn ? "Online" : "Offline";
Console.WriteLine($"User is {status}"); // Print

In the above code, the result of the ternary operator is one of two strings, both of which may be assigned to status variable. The choice of which string to assign depends on the value of the loggedIn variable being true or false. In this case, a value of true results in the first string being assigned, and a value of false results in the second string being assigned.

The above code is equivalent to the following:

bool loggedIn = true;
string status = String.Empty;
if (loggedIn)
  status = "Online";
else
  status = "Offline";

Console.WriteLine($"User is {status}"); // Print

Run Demo


C# switch Statement

The C# switch statement evaluates a single expression against a list of multiple possible cases. Every switch case is related to the single expression and must end with the break or goto case or an empty block. The break statement passes control out of the switch. You can omit a break statement if two cases lead to the same action.

A switch statement starts with the switch keyword followed by a switch expression in parentheses. After the switch expression, you include multiple case labels that represent the possible values of the switch expression. When the switch expression finds the matching value specified by a case label, the statements inside that case are executed.

C# switch statement example

switch Statement flowchart

C# switch statement flowchart

Note: The default case is optional and is executed if no other case applies. It’s also a common practice to code the default label last for easy reading.

In the following example, the value of a number variable is 4. None of the cases matches with the value provided by the switch expression. In this case, the default block is executed which prints out “Unknown number!”

C#'s switch default

Run Demo


C# Iteration Statements

Iteration statement (loop) is a block of code that will repeat itself over and over again until a given condition is true or some terminating condition is reached.

There are four looping structures in C# that enable you to execute a block of code multiple times until a certain condition is met.

for Loop

The C# for loop executes a block of code repeatedly until the condition is false. This type of loop is useful when the number of loop iterations is fixed, and the counter variable that determines how many times the loop is going to be executed is needed in the loop.

C# for loop structure

C#'s for loop structure

C# for loop flowchart

C#'s for loop flowchart

C# for loop starts with the for keyword followed by three expressions separated by semicolons within parentheses.

  • The first parameter declares and initializes a counter variable once at the start.
  • The second parameter is a condition and is evaluated before each new iteration of the loop.
  • The third parameter is an iterator, which prepares the loop for the next iteration.
  • Statements are the block of code that you want to execute multiple times in a loop.

for Loop Example

The following example demonstrates usage of C# for loop. It writes out all the integers from 0 to 4.

C#'s for loop example

Run Demo

The above code consists of:

  1. When the loop is first encountered, C# initializes the counter variable i with the int type and assigns an initial value of 0 to it (i=0).
  2. A Boolean condition (i < 4) will repeatedly execute until the counter is less than 4.
  3. An expression for updating the counter (i++ meaning i=i+1) adds 1 at the end of each repetition of the loop, thus increasing the counter variable by 1.

while Loop

The C# while loop repeatedly executes a block of code inside the loop while the given logical expression is true; otherwise, it breaks. This type of loop is useful when the number of loop iterations does not need to be known before the loop begins, and a counter variable is not needed.

Note: Bear in mind that somewhere in the loop, the expression should be changed to false to avoid an infinite or endless loop.

C# while loop structure

C#'s while structure

C# while loop flowchart

C#'s while loop flowchart

C# while loop starts with the while keyword followed by a single expression within parentheses.

  • Loop takes only one expression.
  • The condition is only evaluated at the beginning of each iteration.
  • The condition (Boolean expression) is evaluated before each new iteration of the loop. This must be true in order for the next iteration to be performed. The iterations end when the condition is false.
  • Set a Boolean flag to false somewhere in the loop to avoid an infinite or endless loop.
  • Loop ends with a semicolon “;“.
  • Statements are the block of code that you want to execute multiple times in a loop.

while Loop Example

The code below shows an example of how a C# while loop works. It writes out all the integers from 1 to 4.

C#'s while loop example

Run Demo

The above code consists of:

  1. Declared and initialized a counter variable with the int type and assigned an initial value of 0 to it, counter=0.
  2. The Boolean expression is evaluated, and if it is true, then the sequence of operations in the body of the loop is executed.
  3. A Boolean condition (counter < 4) will repeatedly execute until the counter is less than 4.
  4. An expression for updating the counter (counter++ is a syntactically-shorter version of counter=counter+1) adds 1 at the end of each repetition, thus increasing the counter variable by 1.

do-while Loop

The C# do-while loop is a variant of the while loop except for one main difference: it will always execute the loop body at least once in the beginning irrespective of the condition being true or false. The condition is evaluated at the end of the first execution of the block when the while statement is encountered.

Note: Bear in mind that somewhere in the loop, the expression should be changed to false to avoid an infinite or endless loop.

C# do-while loop structure

C#'s do-while loop structure

C# do-while loop flowchart.

C#'s do-while loop flow chart

C# do-while loop starts with the do keyword and the loop body. At the bottom of the block is while keyword followed by single expression within parentheses ().

  • Always executes the loop body at least once, even if the condition fails the first time.
  • The condition (Boolean expression) is evaluated after each new iteration of the loop. This must be true in order for the next iteration to be performed. The iterations end when the condition is false.
  • Set a Boolean flag to false somewhere in the loop to avoid an infinite or endless loop.
  • Loop ends with a semicolon “;”.
  • Statements are the block of code that you want to execute multiple times in a loop.

do-while Loop Example

The code below shows an example of how a do-while loop works. It writes out all the integers from 1 to 4.

C#'s do-while loop example

Run Demo

The above code consists of:

  1. Declared and initialized a Counter variable with the int type and assigned an initial value of 0 to it, counter=0.
  2. First time in the beginning, the loop body executes at least once irrespective of the condition being true or false.
  3. The Boolean expression is evaluated at the bottom of the code block when encountered.
  4. The Boolean condition (counter < 4) will repeatedly execute until the counter is less than 4.
  5. An expression for updating the counter (counter++ is a syntactically-shorter version of counter=counter+1) adds 1 at the end of each repetition, thus increasing the counter variable by 1.

foreach Loop

The C# foreach loop provides simple syntax to cycle through all the elements in an array or collection unless you explicitly end the loop with the break command.

C# foreach loop structure

C#'s foreach loop structure

C# foreach loop flowchart

C#'s foreach loop  flowchart

C# foreach loop starts with the foreach keyword followed by parentheses. See the above images.

  • The type is used to declare the data-type of the variable. You can use the var keyword, which instructs the compiler to infer the type of the item from the type of the collection.
  • The item is the looping variable used inside the loop body into which the next element is automatically acquired from the collection on each iteration. The variable (the iterator) data-type must be the same as the items in the array or list.
  • The collection is the array or list representing a number of values over which you want to iterate.
  • The statements are the block of code that executes for each iteration of the loop multiple times.

Note: The compiler only allows reading from, not writing to, the collection during the execution of a foreach loop.

foreach Loop Example

If you have more than one statement within the loop, you must enclose the statements in the opening and closing braces. You can use braces with a single statement as well.

int[] integerValues = { 1, 2, 3, 4 };

foreach (int value in integerValues)
{
  System.Console.WriteLine(value);
}

Run Demo

In the code above, you have an int variable value that is used for looping. Each time the loop runs, an element in the integerValues array is assigned to the variable value. For example, the first time the loop runs, the number 1 is assigned to value. It then executes the code within the block that makes up the foreach loop body. The line System.Console.Write(value); simply prints out the number 1 on the console. In the second iteration, the number 2 is assigned and printed out. This continues until all the elements in the array have been printed. This means that the code inside the C# foreach loop is called as many times as there are elements in the integerValues array. So, if integerValues contains 4 elements, the code inside the loop block will be executed 4 times.


C# String Concatenation

A common use of string concatenation (kon-kat-en-ay-shun) is to inject variable values into the string using the string formatting syntax. C# provides the string operator + (plus symbol) or the String.Format method to format and organize various strings. Both ways can be used to join (concatenate) two or more strings together to generate a new string.

C# String.Concat() and “+”

The variable result in the following example would contain the value a and b after concatenating all the strings.

int a = 2;
int b = 5;

//+ operator concatenates two strings
string result = "Addition of " + a + " + " + b + " is " + (a + b);

Here, a and b are numeric. Operands that are not of type string will be automatically converted to its string representation by calling the virtual ToString method on that operand.

//+ symbol actually translates to the String.Concat() method
string result = String.Concat("Addition of ", a, " + ", b, " is ", (a + b));

OR

string result = string.Concat(new object[] {"Addition of ", a, " + ", b, " is ", (a + b)});

The C# compiler converts the + operator into the static String.Concat() method at compile time; there is no real benefit in choosing one method over the other.

C# String Interpolation (New Way)

C# 6.0 introduced string interpolation which provides another option on how to insert variable values into a string. Now you can insert one or more expressions directly in the string literal just by adding the $ prefix to output the result in a nicely formatted manner. Interpolated strings are more readable and less error-prone than any other previous methods of formatting strings.

C# String Interpolation Format

The following example uses string interpolation to create the string result using the $ prefix. A string with a $ sign can use curly braces {…} around the name of a variable to output the value assigned to it at that position in the string. Without the leading $ symbol, the string {…} would be treated as a string literal.

int a = 2;
int b = 5;

string result = $"Addition of {a} + {b} is {a + b}"; // string interpolation

Run Demo


C# Type Conversion

Conversion of one type to another is called type conversion. There are two conversion mechanisms supported by C#:

Implicit Type Conversion (Hidden)

If one type is converted into another type automatically by the CLR, it’s called implicit type conversion. No special casting syntax is required, and no data is lost during implicit conversion.

C# performs implicit data type conversion when types are compatible, and the compiler knows the conversion is safe. For example, the following code declares an int variable and set its value equal to 100. Because an int can always fit in a double, C# knows this is safe and doesn’t complain.

int i = 786;
double d = i; // Implicit casting from int to double

int i = 57;
// automatic type conversion
long l = i;
float f = l;

char i = '0';
int d = i;

Run Demo

Explicit Type Conversion (Cast)

Explicit conversion is required when the data cannot convert from one simple-type to another automatically by the compiler or when conversion may change the value by producing an incorrect result due to the possible loss of data (narrowing conversions). To prevent a compilation error, the compiler requires you to use a cast operator to perform the type conversion.

Let’s look at different ways of explicit type conversion in C#.

Casting

The parentheses (( )) operator is used to explicitly cast one type to another by forcing the compiler to make the conversion. Casting works only between compatible data types, where CLR knows how to convert from one type to the other.

To perform a cast, put the target data type inside parentheses in front of the value or variable to be converted. If the cast is successful, it returns a value in that type; otherwise, it throws an exception. Take a look at the following example.

Some of the conversions that cannot be made implicitly:

long l = 2222;

// use ( ) operator to convert a type explicitly
int i = (int)l; // Explicit casting from long to int

Run Demo

Converting

You can use the System.Convert class to perform conversions between base types where implicit or explicit casting isn’t possible. This class contains a complete set of static methods for both up level or down-level casting and throws an InvalidCastException for failed conversions while performing a cast from one type to another.

The string supplied must be a valid representation of a number, and that number must be one that won’t cause an overflow. The following code uses the Convert class ToInt32 method to change the string into an int:

string val = "786";

// Conversion from string to int
int result = Convert.ToInt32(val); // Return 786

Run Demo

Parsing

Parsing is used to convert the string type into a primitive value type by using built-in parsers, which are included in all the data structures of the .NET framework. You can use the Parse or TryParse methods to convert a string representation of a number to an integer, such as the System.Int32 type.

The TryParse method which takes two parameters: the first is the string to be parsed, and the second is an int variable with the out keyword to be filled with the value returned if the conversion succeeds.

string val = "786";
int parsedValue;

bool result = Int32.TryParse(val, out parsedValue); // Return True

// With Code block

if (int.TryParse(val, out parsedValue)) {…} else {…}

Run Demo

The Parse method takes a string as a parameter and returns an int if the string contains an integer value.

string val = "786";
Int32.Parse(val); // Return 786

Run Demo


C# Constant, Readonly

C# supports two types of constants:

  • Compile-time constants: The field value of the constant cannot be changed after the initial assignment, and it must, therefore, be assigned a value as it is declared.
  • Run-time constants: The value of the constant can be assigned during run-time; once it’s assigned a value, it can’t be changed.

Note: A constant can be any of the built-in numeric types, bool, char, string, or an enum type.

Constant (Compile-time Constants)

For compile-time constants, you can use the const keyword before the data type to declare a constant field or a constant local to a method, like this:

C# Compile-Time Constant

Run Demo

The const modifier creates a compile-time constant, so the compiler will replace all usage of the constant with its value. Therefore, the value must be assigned at the time of declaration.

Readonly (Run-time Constants)

For run-time constants, use the readonly keyword. For example:

C#'s Run-Time Constant

Run Demo

This modifier may only be applied to fields and can only be initialized either at the declaration or in a constructor but nowhere else.


C# Reference | Microsoft Docs