C# Tutorial For Beginners

C# is an open source, modern, flexible, versatile, and object-oriented programming language. This C# tutorial is for beginners who want to learn C# programming. In this C# tutorial, you’ll learn to write your first C# application, learn about C# data types, C# array, C# string, C# dictionary, C# collections, and other C# features and functionalities.

1. Introduction to C#

 
C# is a simple, modern, and object-oriented programming language developed by Microsoft. C# is an open source project managed by the .NET Foundation. C# is a fully mature object-oriented programming language and allows developers to build cross-platform applications for Windows, Web, and mobile platforms. C# apps can be deployed on Linux, Windows, iOS, and Android operating systems.
 
This tutorial contains the following topics,
  • Introduction to C#
  • Getting Ready
  • First C# Application
  • C# Types
  • Value and Reference Types
  • C# Structs
  • C# Enums
  • C# Class
  • Class Access Modifiers
  • C# Field
  • C# Constructor
  • C# Property
  • C# Method
  • C# Method Overloading
  • C# Expression
  • C# Operator
  • C# Statements
  • C# if else Statement
  • C# switch Statement
  • C# for Statement
  • C# foreach Statement
  • C# do while Statement
  • C# while Statement
  • C# go to Statement
  • C# break Statement
  • C# continue Statement
  • C# return Statement
  • C# Interface
  • C# Partial Class
  • C# Static Class
  • C# Abstract Class
  • C# Array
  • C# String
  • C# Dictionary
  • C# List
  • Summary
 C# Tutorial 
 
C# is a modern programming language. We can use C# to build today’s modern software applications. C# can be used to develop all kind of applications including Windows client apps, components and libraries, services and APIs, Web applications, Mobile apps, cloud applications, and video games.
 
Here is a detailed article: What Can C# Do For You
 
Microsoft supports two software development frameworks, .NET Framework and .NET Core. .NET Framework was launched in 2001 to develop Windows and Web applications. But with the rise of open source trends, Microsoft open sourced language compilers and .NET and the new .NET is called .NET Core. Going forward, there is going to be only one version of .NET, that will be .NET. The next version of .NET is going to be released in 2020, called .NET 5.
 
Here is a detailed article: The Future of .NET
 

2. Getting Ready

 
Before starting your first C# application, you will need an editor or an Integrated Development Environment (IDE), where you can type and compile your code. Visual Studio developed by Microsoft is the best IDE out there for C# developers. The current version of Visual Studio is Visual Studio 2019.
 
Visual Studio 2019 comes in three different flavors – Visual Studio 2019 Enterprise, Visual Studio 2019 Professional, and Visual Studio 2019 Community.
 
Visual Studio 2019 Community edition is a free. We’ll use Visual Studio 2017 Community edition.
 
Alternatively, you may also use Visual Studio Code. Visual Studio Code is a free, lightweight, open source code editor for writing and debugging code. VS Code supports major programming languages.
 
You may download Visual Studio 2017 Community here.
 

3. First C# Application

 
Let’s write our first simple “Hello, World!” program in C#. This is the simplest program you can write in C#. The program will write output on your console saying, “Hello, C# word!”
 
Open Visual Studio 2019 Community.
 
Select File > New > Project.
 
C# Tutorial
 
Select Templates > Visual C# > .NET Core > Console App (.NET Core).
 
C# Tutorial
 
Now, give your project a name by typing a name in the Name TextBox. I name my project, HelloCSharp.
 
Click OK button to create the project.
 
This action creates a console app.
 
C# Tutorial
 
Double click on Program.cs in Solution Explorer and delete everything in the file.
 
Now type the following code.
  1. using System;  
  2. class Hello  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         Console.WriteLine("Hello, C# World!");  
  7.         Console.ReadKey();  
  8.     }  
  9. }  
Build and run. Hit Ctrl+F5.
 
The action compiles and runs your code by creating a HelloCSharp.exe file in your preselected location. The result is “Hello, C# World!” is printed on system console.
 
As you can see in Figure 5, HelloCSharp.exe is created in C:\Mahesh\Csharp\HelloCSharp\bin\Debug\folder.
 
Output looks like this,
 
C# Tutorial
 
Well done!
 

4. C# Types

 
C# is a strongly typed language. Types in C# can be divided into two categories – built-in types and custom types.
 
Built-in types are bool, byte, sbyte, char, decimal, double, float, int, uint, long, ulong, object, short, ushort, and string.
 
The following code in is example of how to declare variables, assign values to them, and use them.
  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {  
  7.         Console.WriteLine("Types Sample");  
  8.         
  9.         // Declare int variable  
  10.         int i = 34;  
  11.         // char variable  
  12.         char c = 'm';  
  13.         // float variable  
  14.         float per = 6.8f;  
  15.         // object variable  
  16.         object o = c;          
  17.         // string varialbe  
  18.         string name = "Mahesh Chand";  
  19.         // Use i in an operation   
  20.         int counter = i + 1;  
  21.         /* Use c in a condition. Check if the value of c is 'm' 
  22.         the print c and counter */  
  23.         if (c == 'm')  
  24.         {  
  25.             Console.WriteLine("i is {0}:", i);  
  26.             Console.WriteLine("counter is {0}:", counter);  
  27.             Console.WriteLine("c is {0}:", c);  
  28.             Console.WriteLine("name is {0}:", name);  
  29.             Console.WriteLine(counter);  
  30.         }  
  31.   
  32.         Console.ReadKey();  
  33.     }  
  34. }  
Learn more here: Introduction To Types In C#
 

5. Value and Reference Types

 
C# supports value and reference types.
 
A value type variable contains the actual data within its own memory allocation. Value types derived from System.ValueType. There are two categories of value types, structs and enum.
 
A reference type is a reference to a memory location where the actual data is stored. The main reference types are class, array, interface, delegate, and event. A null value is assigned to a reference type by default. A type assigned to a null value means the absence of an instance of that type.
 
 

6. C# Structs

 
A struct type is a value type that is typically used to encapsulate a group of variables that are similar. A struct type can declare constructors, constants, fields, methods, properties, indexers, operators, and nested types.
 
The following code is an example of use of a struct Book uses a record for a book with four members, Title, Author, Price, and Year. The Main program creates an object of Book struct, set its member values, and print the values.
  1. using System;  
  2.   
  3. namespace StructSample  
  4. {  
  5.     // Book struct  
  6.     public struct Book  
  7.     {  
  8.         public string Title;  
  9.         public string Author;  
  10.         public decimal Price;  
  11.         public short Year;  
  12.     }  
  13.   
  14.     class Program  
  15.     {  
  16.         static void Main(string[] args)  
  17.         {  
  18.             Console.WriteLine("Struct Sample!");  
  19.   
  20.             // Create a Book object  
  21.             Book myBook = new Book();  
  22.             myBook.Title = "Simplified C#";  
  23.             myBook.Author = "Mahesh Chand";  
  24.             myBook.Price = 45.95M;  
  25.             myBook.Year = 2017;  
  26.   
  27.             Console.WriteLine($"Book {myBook.Title} was written by {myBook.Author}" +  
  28.                $" in {myBook.Year}. Price is {myBook.Price}");  
  29.   
  30.             Console.ReadKey();  
  31.         }          
  32.     }  
  33. }  
Learn more here: Struct In C#
 

7. C# Enums

 
Enums in C# are used to represent a set of constants as integral values. For example, to represent a week day, we know there are only seven days in a week.
 
Here are some common examples of struct types.
  • WeekDay – Mon, Tue, Wed, Thu, Fri, Sat, Sun
  • Months – Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
  • Rectangle – Left, Top, Bottom, Right
  • Point – X, Y
Here are couple of examples of enums.
  1. // Create an enum of week days  
  2. public enum WeekDays { Sun, Mon, Tue, Wed, Thu, Fri, Sat };  
  3.   
  4. // Create an enum of RGB colors  
  5. public enum RGB { Red, Green, Blue };  
Learn more here: Enum In C#
 

8. C# Class

 
Classes are the foundation of an object-oriented programming language such as C#. A class is a logical unit of data. Classes have members such as properties, fields, methods, and events.
 
The following code is a Person class with three private members, name, age, and sex. The class also has three public properties. We will discuss private and public properties shortly. 
  1. // Person class   
  2. class Person  
  3. {  
  4.     // Members of a class  
  5.     private string name;  
  6.     private Int16 age;  
  7.     private string sex;  
  8.   
  9.     // Public properties of a class  
  10.     public string Name  
  11.     {  
  12.         get { return this.name; }  
  13.         set { this.name = value; }  
  14.     }  
  15.     public Int16 Age  
  16.     {  
  17.         get { return this.age; }  
  18.         set { this.age = value; }  
  19.     }  
  20.     public string Sex  
  21.     {  
  22.         get { return this.sex; }  
  23.         set { this.sex = value; }  
  24.     }  
  25. }  
In C#, keyword new is used to create an instance of a class. The following code snippet sets the values of Name, Age, and Sex properties of object p.
  1. p.Name = "Mahesh Chand";  
  2. p.Age = 40;  
  3. p.Sex = "Male";  
The following code now reads the values of the members of object p.
  1. // Print Person details  
  2. Console.WriteLine("The person {0} is {1} years old {2}.", p.Name, p.Age, p.Sex);  

9. Class Access Modifiers

 
Access modifiers are accessibility levels of types and type members and set rules how a type and its members can be used within the type, current assembly, and other assemblies.
 
The following table describes class or struct member accessibility type and their scopes.
 
Access Modifier
Scope
public
The type or members can be accessed by the code in the same assembly or assemblies that reference it.
private
The type or members can be accessed only by code in the same class.
protected
The type or members can be accessed only by code in the same class, or the classes that are derived from it.
internal
The type or members can be accessed by the code in the same assembly but not from other assemblies.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.
private protected
The type of member can be accessed within the same class or the classes derived within the same assembly.
 

10. C# Field

 
A field member is a variable of a class or struct. A field can be public, private, protected, internal, or protected internal.
 
Fields in a class can have different accessibility levels. In the following code, fields name, age, and sex are private fields. That means they can only be accessed within the same class only. Public fields can be accessed from anywhere. Protected fields can be accessed within the Person class and any classes derived from it.
  1. /// Person class   
  2. class Person  
  3. {  
  4.     // Members of a class  
  5.     private string name;  
  6.     private Int16 age;  
  7.     private string sex;  
  8.     protected string book;  
  9.     protected internal int code;  
  10.     public Int16 Year;  
  11. }   
A field member can also be read-only. This means the field can only be assigned in the declaration or in the constructor of the class.
If the field is not static, you have to access fields from the class instance. The code snippet in Listing 20 creates an instance of the Person class and sets the value of Year field.
  1. Person p = new Person();  
  2. p.Year = 2000;  
Listing 20.
 
A field can also be static. That means, the fields can be available to the code without creating an instance of a class. A static field is declared using the static keyword and a readonly field is declared using the readonly keyword. These both keywords can be combined to declare a readonly static field. The following code snippet declares a readonly static variable.
  1. public static readonly string author = "Mahesh Chand";  
Fields can be variables or constants.
 
Learn more here: Fields and Properties in C#
 

11. C# Constructor

 
Constructors are responsible for creating an instance of a class or struct. Constructors are methods with the same name as a class or struct and must be called to create an instance of a class or struct. The constructor is called using the new operator.
 
Let’s look at a simple class Person that has four members.
  1. /// Person class   
  2. class Person  
  3. {  
  4.     // Members of a class  
  5.     private string name;  
  6.     private int age;  
  7.     private string sex;  
  8.     private string profession;  
  9. }  
For example, the following code snippet creates a Person object using the new operator and calls a constructor.
  1. Person p = new Person();  
Once an object is created (p in this case), now it can be used to call other members of ‘p’. For example, the following code snippet sets the value of name of ‘p’.
  1. p.name = "Mahesh Chand";  
Constructors are used to initialize the data members of new objects. A class or struct can have one or more than one constructor. A constructor does not have a return type.
 
 

12. C# Property

 
Property members of a class provides its callers to access a class’s private field members. Property members expose private fields through special methods called accessor. The get accessor is used to return the property value and the set accessor is used to assign a new value to the property.
 
Let’s take a look at the following code that declares the Person class with three private fields, name, age, and sex. The private fields are exposed to the external programs through public properties, Name, Age, and Sex.
  1. /// Person class   
  2. class Person  
  3. {  
  4.     // Members of a class  
  5.     private string name;  
  6.     private int age;  
  7.     private string sex;  
  8.   
  9.     // Constructor  
  10.     public Person()  
  11.     {       
  12.     }  
  13.   
  14.     // Public properties of a class  
  15.     public string Name  
  16.     {  
  17.         get { return this.name; }  
  18.         set { this.name = value; }  
  19.     }  
  20.     public int Age  
  21.     {  
  22.         get { return this.age; }  
  23.         set { this.age = value; }  
  24.     }  
  25.     public string Sex  
  26.     {  
  27.         get { return this.sex; }  
  28.         set { this.sex = value; }  
  29.     }  
  30.   
  31. }  
The following code creates a Person class objects and sets its properties. Once the properties are set, the actual values of the properties actually copied inside the object. The following code reads the properties values and prints them on the console.
  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {  
  7.         // Create a Person object  
  8.         Person p = new Person();  
  9.         // Set Person properties   
  10.         p.Name = "Mahesh Chand";  
  11.          = 40;  
  12.         p.Sex = "Male";  
  13.   
  14.         // Get Person properties   
  15.         Console.WriteLine("Person 1 {0} is {1} years old {2}.", p.Name, p.Age, p.Sex);       
  16.       
  17.         Console.ReadKey();  
  18.     }  
  19. }  
 

13. C# Method

 
A method member of a class is a block of code that performs a specific task. A method signature is a combination of an access modifier followed by an additional modifier, return type, method name, and method parameters. A typical method signature looks like the following, where a public method returns a bool value and takes two parameters. The method’s code block starts with an open bracket ‘{‘ and ends with a closing bracket ‘}.
  1. // Method signature  
  2. public bool MethodName(int param1, string param2)  
  3. {  
  4.     // Implementation   
  5.     return false;  
  6. }  
A method can return a void or a data type. Method can also take arguments and also return multiple values.
 
Let’s add a method, SayHello to our Person class, that prints a message with the person’s name to the console. The method SayHello does not return a value. The final Person class looks like the following.
  1. /// Person class   
  2. class Person  
  3. {  
  4.     // Members of a class  
  5.     private string name;  
  6.     private int age;  
  7.     private string sex;  
  8.     private string profession;  
  9.     private bool retired = false;        
  10.   
  11.     // Overloaded constructor   
  12.     public Person(string personName, int personAge, string personSex)  
  13.     {  
  14.         this.name = personName;  
  15.         this.age = personAge;  
  16.         this.sex = personSex;  
  17.     }  
  18.   
  19.     // Public properties of a class  
  20.     public string Name  
  21.     {  
  22.         get { return this.name; }  
  23.         set { this.name = value; }  
  24.     }  
  25.   
  26.     public int Age  
  27.     {  
  28.         get { return this.age; }  
  29.         set { this.age = value; }  
  30.     }  
  31.     public string Sex  
  32.     {  
  33.         get { return this.sex; }  
  34.         set { this.sex = value; }  
  35.     }  
  36.   
  37.     /// <summary>  
  38.     /// A simple method prints out a message  
  39.     /// </summary>  
  40.     public void SayHello()  
  41.     {  
  42.         if (this.name.Length > 0)  
  43.             Console.WriteLine("Hello {0} from the Person class"this.name);  
  44.     }    
  45. }  
Now let’s call this method from our Main method. As you’ve seen earlier in case of properties and fields, we call a method in a similar way we can any other members of a class or struct. The following code creates an instance of Person class, sets its Name property, and calls SayHello method.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         // Create a Person object  
  7.         Person person = new Person("Mahesh Chand", 40, "male");  
  8.         // Call SayHello method  
  9.         person.SayHello();  
  10.   
  11.         Console.ReadKey();  
  12.     }  
  13. }  
Often times, a caller program needs to pass some data to a class. The passed data may be used for processing, business logic, and decision making. The last portion of a method signature is a list of method parameters that are passed by the caller program.
 
A method defines the type and name of parameters. Multiple parameters are separated by commas.
 
Here is a method that takes three parameters and returns a value.
  1. public decimal CalculateSalary(int hours, decimal rate, decimal bonus)  
  2. {  
  3.     // Payment = number of hours worked * rate + bonus  
  4.     return (hours * rate) + bonus;           
  5. }  
Now let’s call the CalculateSalary method from our Main method.
  1.  // Calculate salary of Person  
  2. decimal salary = person.CalculateSalary(160, 50, 3000);  
  3. Console.WriteLine("{0} gets paid ${1}.", person.Name, salary);  

14. C# Method Overloading

 
C# allows you to declare same name methods differentiated by their signature. This process is called method overloading. The following class RateCalculator declares a method CalculateCost with three different signatures. 
  1. public class RateCalculator  
  2. {  
  3.     private decimal total;  
  4.   
  5.     // Ref return method  
  6.     public decimal CalculateCost(decimal price, decimal rate)  
  7.     {  
  8.         total = price * rate;  
  9.         return total;  
  10.     }  
  11.       
  12.     // Method with an out parameter  
  13.     public void CalculateCost(decimal price, decimal rate, out decimal total)  
  14.     {  
  15.         total = price * rate;  
  16.     }  
  17.   
  18.     // Method with multiple return values  
  19.     public void CalculateCost(decimal price, decimal rate, out decimal total, out decimal min, out decimal max)  
  20.     {  
  21.         min = rate * 0.5m;  
  22.         max = rate * 2;  
  23.         total = price * rate;  
  24.     }  
  25. }  
The call of a method depends on the number and types of arguments passed to the method call. The following code calls these three difference overloaded methods.
  1. // Method overloading sample  
  2. using System;  
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {          
  7.         RateCalculator calculator = new RateCalculator();  
  8.         decimal total = calculator.CalculateCost(12.5m, 6.8m);  
  9.         calculator.CalculateCost(12.5m, 6.8m, out decimal cost);  
  10.         calculator.CalculateCost(12.5m, 6.8m, out decimal totalcost, out decimal minrate, out decimal maxrate);  
  11.         Console.WriteLine("Total cost {0}", totalcost);  
  12.   
  13.         Console.ReadKey();  
  14.     }      
  15. }  
Learn more here: Method Overloading In C#
 

15. C# Expression

 
An expression is a sequence of operators and operands that specify some sort of computation and the result is evaluated in a single value or object. The following code snippet is an example of two expressions.
  1. Convert.ToInt32("12");  
  2. 10 + 5;  
The first expression converts a string “12” to an integer value and the second expression adds two numbers.
 
Typically, expressions are used in statements. For example, the following code snippet is an example of a statement. The right side of the statement is an expression that adds two numbers.
  1. int a = 10 + 5;  
An expression can consist literal values, and method invocations. The following code snippet uses literal names to add in an expression.
  1. string name = "Mahesh" + "Chand";  
An expression can also be used in method invocation. A method invocation requires the name of the method, followed by parenthesis and any method parameters. The following code snippet invokes two methods.
  1. Console.WriteLine("Operators Sample!");  
  2. Console.ReadKey();  
 

16. C# Operator

 
An operator is responsible for an operation. For example, the operators + and - indicate adding and subtracting operands, such as values, objects, and literals. An operand can also be an expression, or any number of sub expressions.
 
The following code is a simple example of operators and operands.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         Console.WriteLine("Operators Sample!");  
  7.   
  8.         // Declare variables   
  9.         int a = 10; int b = 20;  
  10.         decimal d = 22.50m;  
  11.         string first = "Mahesh"string last = "Chand";  
  12.   
  13.         // Use + and - operators to add and subtract values     
  14.         int total = a + b;  
  15.         decimal dTotal = a + b + d;  
  16.         int diff = b - a;  
  17.         Console.WriteLine("diff: " + diff);  
  18.         string name = first + " " + last;  
  19.         Console.WriteLine("Name: " + name);  
  20.   
  21.         Console.ReadKey();  
  22.     }  
  23. }  
The following line is a code expression. The ‘+’ operator applies to two variables, a and b, and the result is stored in variable total.
  1. int total = a + b;  
The code also declares other variables of type decimal, and strings. The following code snippet adds a decimal value to two int values.
  1. decimal dTotal = a + b + d;  
The following code snippet adds two string values. An extra space is also added during the operation.
  1. string name = first + " " + last;  
There are three types of operators, unary, binary, and ternary.
 
Learn more here: Operators in C#
 

17. C# Statements

 
A statement is a part of a program that represents an action such as declaring variables, assigning values, calling methods, loop through a collection, and a code block with brackets. A statement can consist of a single line ends with a semicolon, or a code block enclosed in {} brackets.
 
The following code snippet has two statements.
  1. decimal d = 22.50m;  
  2. string first = "Mahesh";   
Here is an if..else statement with several lines of code.
  1. if (d > 22)  
  2. {  
  3.     d -= 10;  
  4.     Console.WriteLine("d is {0}", d);  
  5. }  
  6. else  
  7. {  
  8.     d += 10;  
  9.     Console.WriteLine("d is {0}", d);  
  10. }  

18. C# if . . .else Statement

 
The if . . .else statement is also known as a conditional statement. Here is the syntax of if..else statements.
  1. if (condition)  
  2. {  
  3. Statement  
  4. }  
  5. else   
  6. {  
  7. Statement  
  8. }  
The if. . .section of the statement or statement block is executed when the condition is true; if it’s false, control goes to the else statement or statement block. The ‘else’ portion of the statement is optional.
 
The following code uses if statement to check if the value of a is less than 0, then display a message, ‘a is negative’.
  1. int a = -1;  
  2. if (a < 0)  
  3. {  
  4.     Console.WriteLine("a is negative.");  
  5. }  
The following code snippet uses if..else statement to check if the value of a is less than 0. If not, then display a message, ‘a is 0 or positive’.
  1. int a = -1;  
  2. if (a < 0)  
  3. {  
  4.     Console.WriteLine("a is negative.");  
  5. }  
  6. else  
  7. {  
  8.     Console.WriteLine("a is 0 or positive.");  
  9. }  
The {} brackets are optional for a single line statement.
  1. if (a < 0)        
  2.     Console.WriteLine("a is negative.");  
  3. else  
  4.         Console.WriteLine("a is 0 or positive.");  
You can have a nested if . . .else statement with one of more else blocks.
 
You can also apply conditional or ( || ) and conditional and (&&) operators to combine more then one condition.
  1. int a = -1; int b = 10; int c;  
  2.   
  3. // Check if both numbers are negative  
  4. if (a < 0 && b < 0)  
  5. {  
  6.     Console.WriteLine("Both a and b are negative.");  
  7. }  
  8. else if (a < 0 || b < 0)  
  9. {  
  10.     Console.WriteLine("One number is negative.");  
  11. }  
  12. else  
  13. {  
  14.     Console.WriteLine("Both numbers are positive.");  
  15. }  
The if..else statement can have other nested statements and also can have more than one if..else statements.
 

19. C# switch Statement

 
C# switch statement is a conditional statement that pairs with one or more case blocks and a default block. The case block of code is executed for the matching value of switch expression value. If the switch value doesn’t match the case value, the default option code is executed.
  1. switch (expression)  
  2. {  
  3.     case expression_value1:  
  4.         Statement  
  5.         break;  
  6.     case expression_value2:  
  7.         Statement  
  8.         break;  
  9.     case expression_value3:  
  10.         Statement  
  11.         break;  
  12.     default:  
  13.         Statement  
  14.         break;  
  15. }  
The expression in the above code can be any non-null expression.
 
The following code is a typical switch statement. The switch expression is a random number between 1 and 9 and based on the value of the expression, a case block is executed. If the value of switch expression is more doesn’t match with first three case values, the default block is executed.
  1. // Generate a random value between 1 and 9  
  2. int caseSwitch = new Random().Next(1, 9);  
  3.   
  4. switch (caseSwitch)  
  5. {  
  6.     case 1:  
  7.         Console.WriteLine("Case 1");  
  8.         break;  
  9.     case 2:  
  10.         Console.WriteLine("Case 2");  
  11.         break;  
  12.     case 3:  
  13.         Console.WriteLine("Case 3");  
  14.         break;  
  15.     default:  
  16.         Console.WriteLine("Value didn’t match earlier.");  
  17.         break;  
  18. }   
Here is a detailed tutorial on switch statement: C# Switch Statement
 

20. C# for Statement

 
The for statement also knows as the for loop executes a block of code.
 
Syntax of for loop:
 
for (initializer; condition; iterator)
statement
 
This code is the simplest example of a for loop. In this code, the variable counter is initialized to value 0. The condition is until counter is less than or equal to 100, add +1 to counter. The code block displays the value of counter to the console.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         Console.WriteLine("for loop Sample!");  
  7.         // For loop from 0 to 100  
  8.         for (int counter = 0; counter <= 100; counter++)  
  9.             Console.WriteLine(counter);  
  10.   
  11.         Console.ReadKey();  
  12.     }  
  13. }  
The initializer defines the initial value to start with and the iterator is the increment or decrement. The following code snippet starts a loop from 10 to less than 100 in increments of 10.
  1. for (int counter = 10; counter <= 100; counter += 10)  
  2. {  
  3.     Console.WriteLine(counter);  
  4. }  
The statement part of the loop has a code of block that will be executed when the condition is met. The following code blocks checks for the even numbers between 10 and 100.
  1. for (int counter = 10; counter <= 100; counter += 10)  
  2. {  
  3.     if (counter % 2 != 0)  
  4.     {  
  5.         Console.WriteLine(counter);  
  6.     }  
  7. }  

21. C# foreach Statement

 
The foreach statement is used to iterate through a collection of items such as an array. The foreach body must be enclosed in {} braces unless it consists of a single statement. We will discuss arrays and collections later in this book.
 
The following code creates an array of odd numbers and uses foreach loop to loop through the array items and read them.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         Console.WriteLine("foreach loop Sample!");  
  7.         int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };  
  8.         foreach (int num in oddArray)  
  9.         {  
  10.             Console.WriteLine(num);  
  11.         }  
  12.   
  13.         Console.ReadKey();  
  14.     }  
  15. }  
Here is an example of for loop that can also be used read an array items.
  1. for (int counter = 0; counter < oddArray.Length; counter++)  
  2. {  
  3.     Console.WriteLine(oddArray[counter]);             
  4. }  
Here is a detailed tutorial on foreach: C# foreach loop
 

22. C# do..while Statement

 
The do..while statement executes a block of code until the specified while condition is false. The code body must be enclosed in {} braces unless it consists of a single statement.
 
The following code continues a loop until the counter is less than 20.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         Console.WriteLine("do..while loop Sample!");  
  7.         int counter = 0;  
  8.         do  
  9.         {  
  10.             Console.WriteLine(counter);  
  11.             counter++;  
  12.         } while (counter < 20);  
  13.   
  14.         Console.ReadKey();  
  15.     }  
  16. }  

23. C# while Statement

 
The while statement executes a block of code until the specified while condition is false. The code body must be enclosed in {} braces unless it consists of a single statement.
 
The following code continues a loop until the counter is less than 20.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main(string[] args)  
  5.     {  
  6.         Console.WriteLine("do..while loop Sample!");  
  7.         int counter = 0;  
  8.         while (counter < 20)  
  9.         {  
  10.             Console.WriteLine(counter);  
  11.             counter++;  
  12.         }   
  13.   
  14.         Console.ReadKey();  
  15.     }  
  16. }  

24. C# go to Statement

 
The goto statement is used when you need to jump to a particular code segment. The following code uses a goto statement to jump from one case block to another once a condition is met. The program reads a string from the console. When you type, ‘Mahesh’, the case statement sends control to case statement, ‘Chand’.
 
Note that when using a go to in a case statement, you don’t have to provide a break (in all other cases, a break statement is mandatory).
  1. using System;  
  2.   
  3. class Program  
  4. {  
  5.     static void Main(string[] args)  
  6.     {  
  7.         Console.WriteLine("Hello World!");  
  8.   
  9.         Console.WriteLine("What is your name? ");  
  10.         string name = Console.ReadLine();  
  11.         switch (name)  
  12.         {  
  13.             case "Mahesh":  
  14.                 Console.WriteLine("My name is Mahesh.");  
  15.                 goto case "Chand";  
  16.             case "Chand":  
  17.                 Console.WriteLine(@"Chand is my last name.");  
  18.                 break;  
  19.             case "Neel":  
  20.                 Console.WriteLine("My name is Neel. ");  
  21.                 break;  
  22.             default:  
  23.                 break;  
  24.         }  
  25.   
  26.         Console.ReadKey();  
  27.     }  
  28. }  

25. C# break Statement

 
The break statement exits from a loop or a switch immediately. The break statement is usually applicable when you need to release control of the loop after a certain condition is met, or if you want to exit from the loop without executing the rest of the loop structure. You use it in for, foreach, while, and do. . . while loop statements. The following code shows the break statement. If condition num == 15 is true, the control will exit from the loop.
  1. // Array of odd numbers  
  2. int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };  
  3. // Loop through array items  
  4. foreach (int num in oddArray)  
  5. {  
  6.     Console.WriteLine(num);  
  7.     // Don't read any number after 15  
  8.     if (num == 15) break;  
  9. }  

26. C# continue Statement

 
Similar to the break statement, the continue statement also works in for, foreach, while, and do . . . while statements. The continue statement causes the loop to exit from the current iteration and continues with the rest of the iterations in the loop.
  1. for (int counter = 0; counter <= 10; counter++)  
  2. {              
  3.     if (counter == 5)  
  4.         continue;  
  5.     Console.WriteLine(counter);  
  6. }  
In the above code, when the condition counter == 5 is true, the control exits from the current iteration and moves to the next iteration.
 

27. C# return Statement

 
The return statement returns from a method before the end of that method is reached. The return statement can either a value or not, depending on the method that calls it.
 
The following code is an example of a return statement. The execution goes to the caller program of the method.
  1. if (counter == 9)  
  2.     return;  

28. C# Interface

 
An interface is a blueprint that an implementing class or struct must implement. An interface contains only the signatures of its members. Interfaces are used by library and component developers when certain blueprint of the classes or structs must be followed by the implementing developers.
 
An interface has the following properties:
  • Any class or struct that implements the interface must implement all its members.
  • An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
  • Interfaces can contain events, indexers, methods, and properties.
  • Interfaces contain no implementation of methods.
  • A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
  • The corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
  • Interfaces can also have base interfaces and an interface can inherited from more than one base interfaces.
Learn more here: Interface In C#
 

29. C# Partial Class

 
Partial classes were introduced in C# 2 that allows developers to split a class into multiple physical files. Partial classes come handy in large projects and a class size is too large and functionality is distributed among multiple members in a team.
 
In large projects, multiple team members work on same area of functionality. Let’s assume that an application has a user interface (UI), a window or a page. The UI has ton of functionality where multiple developers needs to work on the same window functionality. One developer will create the user interface, change design and layout, while other two developers may work on the database and business logic functionality. We can easily separate the window code into three physical partial classes and each developer can work on a separate class.
 
 

30. C# Static Class

 
Static classes don’t have instance constructors and are used direct without creating an instance. Here are static classes properties.
  • A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator.
  • A static class is a sealed class. That means you cannot inherit any class from a static class.
  • A static class can have static members only. Having non-static member will generate a compiler error.
  • A static class is cannot contain instance constructors.
  • A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.
Learn more here: Static Class In C#
 

31. C# Abstract Class

 
The purpose of an abstract class is to define a blueprint of derived classes. Abstract classes do not have any implementation. The classes that are inherited from an abstract class implements the class functionality.
 
Here are the key characteristics of abstract classes:
  • An abstract class cannot be instantiated.
  • A class may inherit one abstract class only.
  • An abstract class may contain abstract methods, properties, and events.
  • An abstract class can’t be modified with the sealed class modifier.
  • A derived from an abstract class must implement all inherited abstract methods and accessors.
Learn more here: Abstract Class In C#
 

32. C# array

 
An Array in C# is a collection of objects or types. C# Array elements can be of any type, including an array type. An array can be Single-Dimensional, Multidimensional or Jagged. A C# Array can be can be declared as fixed length or dynamic. An Array in C# can be a single dimension, multi dimension, or a jagged array. Learn how to work with arrays in C#.
 
In C#, an array index starts at zero. That means the first item of an array starts at the 0thposition. The position of the last item on an array will total number of items - 1. So if an array has 10 items, the last 10th item is at 9th position.
 
In C#, arrays can be declared as fixed length or dynamic. A fixed length array can store a predefined number of items. A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.
 
The following code snippet creates an array of 3 items and values of these items are added when the array is initialized. 
  1. // Initialize a fixed array    
  2. int[] staticIntArray = new int[3] {1, 3, 5};     
Here is a detailed tutorial on Arrays: Working with Arrays In C#
 

33. C# string

 
The System.String data type represents a string in .NET. A string class in C# is an object of type System.String. The String class in C# represents a string.

The following code creates three strings with a name, number, and double values. 
  1. // String of characters    
  2. System.String authorName = "Mahesh Chand";    
  3.     
  4. // String made of an Integer    
  5. System.String age = "33";    
  6.     
  7. // String made of a double    
  8. System.String numberString = "33.23";    
Here is the complete example that shows how to use stings in C# and .NET.
  1. using System;    
  2. namespace CSharpStrings    
  3. {    
  4.     class Program    
  5.     {    
  6.         static void Main(string[] args)    
  7.         {    
  8.             // Define .NET Strings    
  9.             // String of characters    
  10.             System.String authorName = "Mahesh Chand";    
  11.     
  12.             // String made of an Integer    
  13.             System.String age = "33";    
  14.     
  15.             // String made of a double    
  16.             System.String numberString = "33.23";    
  17.     
  18.             // Write to Console.    
  19.             Console.WriteLine("Name: {0}", authorName);    
  20.             Console.WriteLine("Age: {0}", age);    
  21.             Console.WriteLine("Number: {0}", numberString);    
  22.             Console.ReadKey();    
  23.         }    
  24.     }    
  25. }   
Here is a detailed tutorial on strings: String In C#
 

34. C# List

 
List<T> class in C# represents a strongly typed list of objects. List<T> provides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List<T>, T is the type of objects.
 
List<T> is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List<T> class.
  1. using System.Collections.Generic;    
List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the list, also known as capacity. If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array. You can also pass an initial collection of elements when initialize an object. 
 
This code snippet 1 creates a List of Int16 and a list of string types. The last part of the code creates a List<T> object with an existing collection.
  1. // List with default capacity    
  2. List<Int16> list = new List<Int16>();    
  3. // List with capacity = 5    
  4. List<string> authors = new List<string>(5);    
  5. string[] animals = { "Cow""Camel""Elephant" };    
  6. List<string> animalsList = new List<string>(animals);    
As you can see from Listing 1, the List<string> has an initial capacity set to 5 only. However, when more than 5 elements are added to the list, it automatically expands. 
 
Here is a detailed tutorial on list. C# List Tutorial
 

35. C# dictionary

 
The Dictionary type represents a collection of keys and values pair of data. 
 
C# Dictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection.
 
Before you use the Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line.
  1. using System.Collections.Generic;    
The Dictionary class constructor takes a key data type and a value data type. Both types are generic so it can be any .NET data type.
 
The following The Dictionary class is a generic class and can store any data types. This class is defined in the code snippet creates a dictionary where both keys and values are string types.
  1. Dictionary<stringstring> EmployeeList = new Dictionary<stringstring>();  
The following code snippet adds items to the dictionary.
  1. EmployeeList.Add("Mahesh Chand""Programmer");      
  2. EmployeeList.Add("Praveen Kumar""Project Manager");      
  3. EmployeeList.Add("Raj Kumar""Architect");      
  4. EmployeeList.Add("Nipun Tomar""Asst. Project Manager");      
  5. EmployeeList.Add("Dinesh Beniwal""Manager");      
Here is a detailed tutorial on dictionary: Dictionary In C# 
 

36. Summary

 
This tutorial is an introduction to C# language for beginners. In this tutorial, we learned how to write our first C# program, basics of data types, classes, objects, and class members.
 
Download free C# Programming eBook: