C# for Absolute Beginners: The Basics
In this article, learn everything you need to know in order to master the basics on your way to becoming an ace at C#.
Join the DZone community and get the full member experience.
Join For FreeThis article was originally published in August 2019.
The objective of this article is to familiarize you with the C# programming basics. This article is for absolute beginners who want to learn C# fundamentals.
C# Online Editors
There are many C# online editors out there, you can use for coding, but I have selected two for this article. I have used both editors extensively for preparing this step-by-step tutorial, and they worked very well for me. All the editors are lightweight and free to use in the browser.
I don't know about you guys, but I want a few basic things in an online C# editor.
First, it should have a Simple and Clean Interface. I don't wanna 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 IntelliSense support, which can provide smart completion based on variable types, function definitions, etc.
Lastly, I want Syntax Highlighting to improve code readability.
Variables in C#
"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 data type, which indicates a specific type of value, such as string, int, float, and so on. Always assign a value to a variable before using it to avoid a compile-time error.
C# Variable Naming Conventions
Rules regarding variable names that must be followed are:
- 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;
Type must be a valid data type; 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 a 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;
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;
Var Variable in C# (Type Inference)
To declare implicitly typed local variable, use the var keyword:
var name = "Pirzada";
var age = 35;
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 variable from the expression on the right side of the initialization statement. The compiler then 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
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.
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
*/
C# If-Else Statement
C# if-else statement is one of the most commonly used control flow statements. With if statements, you can tell the computer to make a choice by evaluating a Boolean logical expression (true or false) called a 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 Example:
The value of the number variable is eight. So, the expression (number > 7)
is evaluated to true because eight is greater than seven. Hence, the statements inside the body of the if block is executed. If you change the value of the number variable from eight to six, then the expression will return false, and body of the if statement will not execute.
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
If-Else Condition Example:
The value of a number variable is six. So, the expression (number > 7)
is evaluated to false because six is less than seven. Hence, the code inside the else block is executed.
Else If Statement
A 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:
Note: The order of tests is important if you are using an if else-if construct.
if else-if else Condition Example:
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 — 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 (If-Else Shorthand)
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.
C# Ternary operator:
C# Ternary operator flowchart:
The 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 code above, the result of the ternary operator is one of two strings, both of which may be assigned to thestatus
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
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.
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 four. None of the cases matches the value provided by the switch expression. In this case, the default block is executed which prints out "Unknown number!"
Iteration Statements
An iteration statement (loop) is a block of code that will repeat itself 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
- while loop
- do…while loop
- foreach loop
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; 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# for loop flowchart:
The 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 the usage of C# for loop. It writes out all the integers from zero to four.
The above code consists of:
- When the loop is first encountered, C# initializes the counter variable
i
with the int type and assigns an initial value of zero to it(i=0)
. - A Boolean condition
(i < 4)
will repeatedly execute until the counter is less than four. - An expression for updating the counter (
i++
meaningi=i+1
) adds 1 at the end of each repetition of the loop, thus increasing the counter variable by one.
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 — 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# while loop flowchart:
The C# while loop starts with the while keyword followed by a single expression within parentheses.
- The 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.
- The 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.
The above code consists of:
- Declared and initialized a counter variable with the int type and assigned an initial value of zero to it,
counter=0
. - The Boolean expression is evaluated, and if it is true, then the sequence of operations in the body of the loop is executed.
- A Boolean condition
(counter < 4)
will repeatedly execute until the counter is less than four. - 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 one.
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 at 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# do-while loop flowchart:
The do-while loop starts with the do keyword and the loop body. At the bottom of the block is the while keyword followed by a 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.
- The 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 one to four.
The above code consists of:
- Declared and initialized a Counter variable with the int type and assigned an initial value of 0 to it,
counter=0
. - In the first execution, the loop body executes at least once irrespective of the condition being true or false.
- The Boolean expression is evaluated at the bottom of the code block when encountered.
- The Boolean condition
(counter < 4)
will repeatedly execute until the counter is less than four. - 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 one.
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# foreach loop flowchart:
The 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);
}
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 one 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, number two 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 four elements, the code inside the loop block will be executed four times.
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 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
Type Conversion
Conversion of one type to another is called type conversion. There are two conversion mechanisms supported by C#:
- Implicit Type Conversion.
- Explicit Type Conversion.
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 sets 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;
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.
- Converting.
- Parsing.
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
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 and 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
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 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 {...}
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
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:
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:
This modifier may only be applied to fields and can only be initialized either at the declaration or in a constructor but nowhere else.
Related Articles
Published at DZone with permission of Pirzada .Rashid. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments