C# Tutorial
C# Tutorial
Article
C# Tutorial
By C# Curator on Jul 09, 2023
This C# tutorial is for students and beginners who want to learn C# programming. Basic requirement to learn C# is basic
understanding of programming and some general concepts of object oriented programming. If you're new to OOP, I recommed
learning basics of OOP here, Introduction to Object Oriented Programming.
In this tutorial:
1. Introduction to C#
2. Getting Ready
3. First C# Application
4. C# Types
5. Value and Reference Types
6. C# Structs
7. C# Enums
8. C# Class
9. Class Access Modifiers
10. C# Field
11. C# Constructor
12. C# Property
13. C# Method
14. C# Method Overloading
15. C# Expression
16. C# Operator
17. C# Statements
18. C# if else Statement
19. C# switch Statement
20. C# for Statement
21. C# foreach Statement
22. C# do while Statement
23. C# while Statement
24. C# go to Statement
25. C# break Statement
26. C# continue Statement
27. C# return Statement
28. C# Interface
29. C# Partial Class
30. C# Static Class
31. C# Abstract Class
32. C# Array
33. C# String
34. C# Dictionary
35. C# List
36. Summary
1. Introduction to C#
about:blank 1/19
11/28/23, 8:50 AM C# Tutorial
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.
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.
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.
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.
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!”
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.
C# Tutorial
Double click on Program.cs in Solution Explorer and delete everything in the file.
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, C# World!");
Console.ReadKey();
}
}
C#
Copy
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.
about:blank 2/19
11/28/23, 8:50 AM C# Tutorial
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.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Types Sample");
Console.ReadKey();
}
}
C#
Copy
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.
using System;
about:blank 3/19
11/28/23, 8:50 AM C# Tutorial
namespace StructSample
{
// Book struct
public struct Book
{
public string Title;
public string Author;
public decimal Price;
public short Year;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Struct Sample!");
Console.ReadKey();
}
}
}
C#
Copy
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.
C#
Copy
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.
// Person class
class Person
{
// Members of a class
private string name;
private Int16 age;
about:blank 4/19
11/28/23, 8:50 AM C# Tutorial
private string sex;
C#
Copy
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.
C#
Copy
The following code now reads the values of the members of object p.
C#
Copy
The following table describes class or struct member accessibility type and their scopes.
Access
Scope
Modifier
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 The type or member can be accessed by any code in the assembly in which it is declared, or from within a
internal derived class in another assembly.
private
The type of member can be accessed within the same class or the classes derived within the same assembly.
protected
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.
about:blank 5/19
11/28/23, 8:50 AM C# Tutorial
protected internal int code;
public Int16 Year;
}
C#
Copy
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.
C#
Copy
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.
C#
Copy
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.
C#
Copy
For example, the following code snippet creates a Person object using the new operator and calls a constructor.
C#
Copy
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’.
C#
Copy
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.
about:blank 6/19
11/28/23, 8:50 AM C# Tutorial
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.
// Constructor
public Person()
{
}
C#
Copy
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.
using System;
class Program
{
static void Main(string[] args)
{
// Create a Person object
Person p = new Person();
// Set Person properties
p.Name = "Mahesh Chand";
= 40;
p.Sex = "Male";
Console.ReadKey();
}
}
C#
Copy
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 ‘}.
// Method signature
public bool MethodName(int param1, string param2)
{
// Implementation
about:blank 7/19
11/28/23, 8:50 AM C# Tutorial
return false;
}
C#
Copy
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.
// Overloaded constructor
public Person(string personName, int personAge, string personSex)
{
this.name = personName;
this.age = personAge;
this.sex = personSex;
}
/// <summary>
/// A simple method prints out a message
/// </summary>
public void SayHello()
{
if (this.name.Length > 0)
Console.WriteLine("Hello {0} from the Person class", this.name);
}
}
C#
Copy
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.
using System;
class Program
{
static void Main(string[] args)
{
// Create a Person object
Person person = new Person("Mahesh Chand", 40, "male");
// Call SayHello method
person.SayHello();
Console.ReadKey();
}
}
about:blank 8/19
11/28/23, 8:50 AM C# Tutorial
C#
Copy
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.
C#
Copy
Now let’s call the CalculateSalary method from our Main method.
C#
Copy
C#
Copy
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.
about:blank 9/19
11/28/23, 8:50 AM C# Tutorial
Console.ReadKey();
}
}
C#
Copy
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.
Convert.ToInt32("12");
10 + 5;
C#
Copy
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.
int a = 10 + 5;
C#
Copy
An expression can consist literal values, and method invocations. The following code snippet uses literal names to add in an
expression.
C#
Copy
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.
Console.WriteLine("Operators Sample!");
Console.ReadKey();
C#
Copy
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.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Operators Sample!");
// Declare variables
int a = 10; int b = 20;
decimal d = 22.50m;
string first = "Mahesh"; string last = "Chand";
Console.ReadKey();
about:blank 10/19
11/28/23, 8:50 AM C# Tutorial
}
}
C#
Copy
The following line is a code expression. The ‘+’ operator applies to two variables, a and b, and the result is stored in variable total.
int total = a + b;
C#
Copy
The code also declares other variables of type decimal, and strings. The following code snippet adds a decimal value to two int values
decimal dTotal = a + b + d;
C#
Copy
The following code snippet adds two string values. An extra space is also added during the operation.
C#
Copy
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.
decimal d = 22.50m;
string first = "Mahesh";
C#
Copy
if (d > 22)
{
d -= 10;
Console.WriteLine("d is {0}", d);
}
else
{
d += 10;
Console.WriteLine("d is {0}", d);
}
C#
Copy
if (condition)
{
Statement
}
else
{
Statement
}
C#
Copy
about:blank 11/19
11/28/23, 8:50 AM C# Tutorial
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’.
int a = -1;
if (a < 0)
{
Console.WriteLine("a is negative.");
}
C#
Copy
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’.
int a = -1;
if (a < 0)
{
Console.WriteLine("a is negative.");
}
else
{
Console.WriteLine("a is 0 or positive.");
}
C#
Copy
if (a < 0)
Console.WriteLine("a is negative.");
else
Console.WriteLine("a is 0 or positive.");
C#
Copy
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 than one condition.
C#
Copy
The if..else statement can have other nested statements and also can have more than one if..else statements.
switch (expression)
{
case expression_value1:
Statement
break;
case expression_value2:
about:blank 12/19
11/28/23, 8:50 AM C# Tutorial
Statement
break;
case expression_value3:
Statement
break;
default:
Statement
break;
}
C#
Copy
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.
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
default:
Console.WriteLine("Value didn’t match earlier.");
break;
}
C#
Copy
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.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("for loop Sample!");
// For loop from 0 to 100
for (int counter = 0; counter <= 100; counter++)
Console.WriteLine(counter);
Console.ReadKey();
}
}
C#
Copy
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.
about:blank 13/19
11/28/23, 8:50 AM C# Tutorial
for (int counter = 10; counter <= 100; counter += 10)
{
Console.WriteLine(counter);
}
C#
Copy
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.
C#
Copy
The following code creates an array of odd numbers and uses foreach loop to loop through the array items and read them.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("foreach loop Sample!");
int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };
foreach (int num in oddArray)
{
Console.WriteLine(num);
}
Console.ReadKey();
}
}
C#
Copy
Here is an example of for loop that can also be used read an array items.
C#
Copy
The following code continues a loop until the counter is less than 20.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("do..while loop Sample!");
int counter = 0;
do
{
Console.WriteLine(counter);
about:blank 14/19
11/28/23, 8:50 AM C# Tutorial
counter++;
} while (counter < 20);
Console.ReadKey();
}
}
C#
Copy
The following code continues a loop until the counter is less than 20.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("do..while loop Sample!");
int counter = 0;
while (counter < 20)
{
Console.WriteLine(counter);
counter++;
}
Console.ReadKey();
}
}
C#
Copy
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).
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
C#
Copy
about:blank 15/19
11/28/23, 8:50 AM C# Tutorial
C#
Copy
C#
Copy
In the above code, when the condition counter == 5 is true, the control exits from the current iteration and moves to the next iteration.
The following code is an example of a return statement. The execution goes to the caller program of the method.
if (counter == 9)
return;
C#
Copy
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.
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.
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
about:blank 16/19
11/28/23, 8:50 AM C# Tutorial
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.
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.
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.
C#
Copy
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.
// String of characters
System.String authorName = "Mahesh Chand";
C#
Copy
Here is the complete example that shows how to use stings in C# and .NET.
about:blank 17/19
11/28/23, 8:50 AM C# Tutorial
using System;
namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
// Define .NET Strings
// String of characters
System.String authorName = "Mahesh Chand";
// Write to Console.
Console.WriteLine("Name: {0}", authorName);
Console.WriteLine("Age: {0}", age);
Console.WriteLine("Number: {0}", numberString);
Console.ReadKey();
}
}
}
C#
Copy
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.
using System.Collections.Generic;
C#
Copy
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.
C#
Copy
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.
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.
using System.Collections.Generic;
about:blank 18/19
11/28/23, 8:50 AM C# Tutorial
C#
Copy
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.
C#
Copy
C#
Copy
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.
about:blank 19/19