C# Basics You Must Know

C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft as part of its .NET initiative, which is led by Anders Hejlsberg. This tutorial will teach you basic C# programming as well as various advanced concepts related to the C# programming language using code examples. This tutorial was created for beginners to help them understand the fundamentals of C# programming. 

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

History of C#

C# was first introduced with the.NET Framework 1.0 in 2002 and has evolved significantly since then. The table below summarises the key features introduced in each version of C#:

Version 

.NET Framework

Visual Studio

Important Features


C# 1.0

.NET Framework 1.0/1.1

Visual Studio .NET 2002

Basic features

C# 2.0

.NET Framework 2.0

Visual Studio 2005

  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types

C# 3.0

.NET Framework 3.0\3.5

Visual Studio 2008

  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods

C# 4.0

.NET Framework 4.0

Visual Studio 2010

  • Dynamic binding (late binding)
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types

C# 5.0

.NET Framework 4.5

Visual Studio 2012/2013

  • Async features
  • Caller information

C# 6.0

.NET Framework 4.6

Visual Studio 2013/2015

  • Expression Bodied Methods
  • Auto-property initializer
  • name of Expression
  • Primary constructor
  • Await in the catch block
  • Exception Filter
  • String Interpolation

C# 7.0

.NET Core 2.0

Visual Studio 2017

  • out variables
  • Tuples
  • Discards
  • Pattern Matching
  • Local functions
  • Generalized async return types

C# 8.0

.NET Core 3.0

Visual Studio 2019

  • Readonly members
  • Default interface methods
  • Using declarations
  • Static local functions
  • Disposable ref structs
  • Nullable reference types

C# 9.0

.NET 5.0

Visual Studio 2019

  • Records
  • Init-only properties
  • Top-level statements
  • Init accessors and readonly fields
  • With-expressions
  • Value-based equality

C# 10.0

.NET 6.0

Visual Studio 2022

  • Record structs
  • Global using directives
  • File-scoped namespace declaration
  • Extended Property Patterns
  • Null Parameter Checking
  • Constant interpolated strings

After understanding the history of the c# programming language, we will now understand the introduction of c# in this c# basic tutorial.

Introduction to C#

The letter C# is pronounced "C-Sharp." It is a Microsoft object-oriented programming language that runs on the .NET Framework. C# has roots in the C family and is related to other popular languages such as C++ and Java. In 2002, the first version was released.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Use of C#

  • Applications for mobile devices
  • Applications for the desktop
  • Web-based applications
  • Web-based services
  • Websites, Games, VR Databases, and Applications
  • And so much more!

Why Should You Use C#?

  • It is one of the most widely used programming languages on the planet.
  • It is simple to learn and use.
  • It has a lot of community support.
  • C# is an object-oriented programming language that gives programs a clear structure and allows code to be reused, lowering development costs.
  • Because C# is similar to C, C++, and Java, it is simple for programmers to switch to C# or vice versa.

We will now look at c# syntax after understanding the introduction to the c# programming language in this c# basics article.

C# Syntax

C#_syntax

The syntax of the c# programming languages is as follows:

Line 1: Using System allows us to use classes from the System namespace.

Line 2: A namespace is a container for classes and other namespaces used to organize your code.

Line 3: The curly braces indicate the start and end of a code block.

Line 4: A class is a data and method container that adds functionality to your program. Every line of code in C# must be contained within a class. In our example, the class was called a program.

Line 5: The Main method is another thing that is always present in a C# program. Any code contained within its curly brackets will be executed.

Line 6: Console is a System namespace class with a WriteLine() method for outputting/printing text. In our case, it will print "Hello World!"

Following the c# basics article, we will now look at writing comments in the c# programming language.

C# Comments

Comments can be used to explain and improve the readability of C# code and can also be used to prevent execution when experimenting with different codes.

  • Single-Line Comment

Single-line comments are preceded by two forward slashes (/). C# ignores any text between / and the end of the line (will not be executed).

In this example, a single-line comment is used before a line of code:

// This is a comment

Console. WriteLine ("Hello Simplilearn”);

  • Multi-Line Comment

Comments that span multiple lines begin with /* and end with */. C# will ignore any text between /* and */.

To explain the code in this example, a multi-line comment (a comment block) is used:

/* This is a multi-line comment, and this statement will print hello Simplilearn. */

Console. WriteLine ("Hello Simplilearn ");

After learning how to write c# comments, look at c# variables in this c# basics article.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

C# Variables

Variables are storage containers for data values. In C#, there are different types of variables (defined with different keywords), such as:

  • Int : Integers (whole numbers) without decimals, such as 123 or -123.
  • Double : Stores floating-point numbers with decimal places, such as 19.99 or -19.99
  • char : Holds single characters like 'a'  b.' 'single quotes are used to surround char values.
  • String : A string that stores text, such as "H" in hello World." "double quotes are used to surround string values.
  • bool : Stores values that can be true or false

Declaring Variable

To make a variable, you must first specify its type and then assign it a value:

Syntax

type variable name = value

Example:

int name1 = “xyz”

Console. WriteLine(name1)


Where type is a C# type (for example, int or string) and the variable name is the variable name (such as a or name). To assign values to variables, use the equal sign.

Following on from the c# basics article, we will now look at the various data types in the c# programming language.

C# Data Types

Data types can be categorized based on their memory location:

  • Value Types

  • Reference Types
  • Pointer Types

Using an example, let's go over these c# data types in greater detail.

  • Value Types

A data type is a value type if it can store data values in its own memory space. It means that these data type variables directly contain values.

Example: int i = 200;

The following data types are all of value data type:

Bool, byte, char, decimal, double, Enum, float, int, long, short, and struct

  • Reference Types

Unlike a value type, a reference type does not store its value directly. Instead, it saves the address where the value is kept. In other words, a reference type contains a pointer to another memory location where the data is stored.

Example: string name= “ "Simplilearn”;

The following data types are all of value data type:

String, arrays, classes, and delegate

  • Pointer Types

A simple data type is a pointer type. Its functionality is identical to that of a pointer in C, and it is intended to store the address of another pointer.

Example: int * p; 

The following section of the c# basics article will look at different types of operators in the c# programming language.

C# Operators

Operators are used to manipulating variables and values

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operations
  • Logical Operators

Using an example, let's go over all of these different types of C# operators in greater depth.

  • Arithmetic Operators

Arithmetic operators are commonly used to perform mathematical operations.

Addition (+)

Adds value together 

A + B

Subtraction(-)

Subtracts one value from another

A – B

Multiplication (*)

Multiplies two value

A*B

Division(/)

Divides one value by another

A/B

Modulus (%)

Returns the division remainder

A%B

Increment(++)

Increment the value by one

A++

Decrement(--)

Decrement the value by one

A–

  • Assignment Operators

Variables are assigned values using assignment operators:

=

A=5

+=

A=A+5

-=

A=A-5

*=

A=A*5

/=

A=A/5

%/

A=A%5

&/

A=A&5

  • Comparison Operators

To compare two Values, comparison operators are used:

==

Equal to

!=

Not equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

  • Logical Operators

To determine the logic between variables or values, logical operators are used:

&&

AND

If both statements are factual, this function returns true.

||

OR

If one of the statements is true, this function returns true.

!

NOT

Reverse the result, returning false if it is true.

Following on from the c# operators, we will now look at the structure of a c# program in the c# basics article.

Structure of C# Program

The essential C# programming language structure is defined as:

  • Class
  • Simplilearn
  • Main
  • Void
  • Static
  • Strings[  ]args
  • System.Console.Writeline( “message” );

namespace Simplilearn

{

    class Hello {         

        static void Main(string[] args)

        {

            System.Console.WriteLine("Message");

        }

    }

}

In this c# basics article, we will look at c# conditional statements after understanding the structure of the c# programming language.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

C# Conditional Statement

The programmer must specify one or more conditions to be evaluated or tested by the program, a statement or statements to be performed if the condition is accurate, and optionally other statements to be achieved if the state is determined to be false.

The conditional statements in C# are as follows:

In great detail, we will go over all of these conditional statements in the C# programming language.

  • If Statement

In the C# programming language, an if statement is defined as a programming conditional statement that, if true, performs an operation or displays information within the statement block.

Syntax :

If (condition)

{

    //block of code to be executed if the condition is true

}

conditional-statement-in-c#-basics

  • If-else Statement

In C#, the if-else statement performs operations based on a specific condition. For example, if the given situation is actual, the procedures specified in the if block are executed; otherwise, the else block is performed.

Syntax :

if (condition)

{

  // block of code to be performed if the condition is actual

else 

{

  // block of code to be performed if the condition is actual

}

conditional-statement-in-c#-basics1

  •  If-else-if Ladder

In C#, the if-else statement performs operations based on a specific condition. For example, if the given situation is actual, the procedures specified in the if block are executed; otherwise, the else block is performed.

Syntax :

if (condition1)

{

  // block of code to be performed if condition1 is actual

else if (condition2) 

{

  // block of code to be performed if the condition1 is false and condition2 is actual

else

{

  // block of code to be performed if the condition1 is false and condition2 is False

}

conditional-statement-in-c#-basics2

  • Nested if

In the C# programming language, a nested if statement is defined as a conditional programming statement that includes another if statement inside the previous if statement.

Syntax 

if (boolean expression)

{

if (nested expression 1)

{

// code to be performed

}

else

{

// code to be performed

}

}

else

{

if (nested-expression 2)

{

// code to be performed

}

else

{

// code to be performed

}

}

conditional-statement-in-c#-basics3

  • Switch Case

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

In the C# programming language, a switch case is defined as a programming selection statement that checks for a possible match to the provided condition against the available cases. If none of the cases match, the control will run the default statement block.

Syntax 

switch(expression) 

{

  case a:

    // code block to perfromed

    break;

  case b:

    // code block to perfromed

    break;

  default:

    // code block to perfromed

    break;

}

conditional-statement-in-c#-basics4

In C#, the loop control statement performs looping operations until the given condition is met. The controls are removed from the loop statements when the state is false.

A better comprehension We will now learn about different types of if c# loops after learning about c# conditional statements.

C# Loops

In C#, the loop control statement performs looping operations until the given condition is met. The controls are removed from the loop statements when the state is false.

There are three types of loop in C# language that is given below:

  • for loop

  • while loop
  • do-while loop

In great detail, we will go over all of these loops in the c# programming language.

  • For Loop

The for-loop statement executes a series of messages multiple times and shortens the code that manages the loop variable.

Syntax 

for (statement 1; statement 2; statement 3) 

{

  // code block to be executed

}

Statement 1 is executed (once) before the code block is executed.

Statement 2 specifies the condition under which the code block will be executed. After the code block has been executed

Statement 3 is executed (every time).

loops-in-c#-basics

  • While Loops

While loops repeat a statement or all statements, if a given condition is actual, it checks the condition before executing the loop body.

Syntax :

while (condition) 

{

  // code block to be performed

}

loops-in-c#-basics1.

  • Do While Loops

The do-while loop is an alternative to the while loop. This loop will execute the code block once before checking to see if the condition is actual, and then it will loop as long as the situation is real.

Syntax :

do 

{

  // code block to be executed

}

while (condition);

Following the c# basics tutorial, we will now learn about c# arrays.

Master Core Java 8 Concepts, Java Servlet & More!

Java Certification TrainingENROLL NOW
Master Core Java 8 Concepts, Java Servlet & More!

C# Arrays

A fixed-size sequential collection of elements of the same type is stored in an array. For example, an array holds a collection of the same data type. Still, it is often more helpful to think of an array as a collection of variables of the same type stored in contiguous memory locations.

Instead of declaring individual variables like array0, array1,..., and array99, you declare one array variable like an array and use array[0], array[1],..., array[99] to represent individual variables. For example, an index is used to access a specific element in an array.

C#-arrays-in-c#-basics

Array Declaration 

In C#, you can declare an array using the following syntax:

Syntax :

datatype[ ] array name;

The data type keyword specifies the type of elements in an array.

The array's rank is specified by []. The level determines the array size.

Array name specifies the array's name.

Example: int[ ] array; 

Array Initialization

Declaring an array does not cause the array to be initialized in memory. After the array variable has been initialized, you can assign values to it.:

Syntax :

The array is a reference type, so you need to use the new keyword to create an array instance.

Example : int[ ] numbers = new numbers[20]

Following our understanding of c# arrays, we will now look at c# strings in this c# basics article.

C# Strings

A string is a String object with the value text. The text is internally stored as a sequential read-only collection of Char objects. Because there is no null-terminating character at the end of a C# string, it can contain any number of embedded null characters ('0').'

Syntax :

Char[ ] nameofstring = { ‘a’ , ‘b’ , ‘c’ , \0};

Example :char[ ] name ={‘S,’ ‘I’, ‘M’, ‘P’, ‘L’, ‘I’, ‘L’, ‘E’, ‘A’, ‘R’, ‘N’ , \0};

S

I

M

L

I

L

E

A

R

N

\0

Some string functions and descriptions are provided below.

clone( ) : Returns the reference of string.

Compare() : compare two specific strings.

Concat( ): Joins two strings and store the result in the first string

Contains( ): Return the value of specified string

CopyTo( ): Copies character from the specified position

Equals( ): Determines the two string objects have the same value

Trim( ) : Trims the string

In this c# basics tutorial, we will learn how to define and call a function, which will be described in our next segment, c# function.

C# Functions

A method is a collection of statements that work together to complete a task. For example, every C# program contains at least one class with the primary process.

To use a method in C#, you need to:

  • Define a method
  • Call the method

When you define a method, you are essentially declaring the elements that make up its structure:

Syntax 

<Access Specifier> <Return Type> <Method Name>(Parameter List)

{   Method Body }

Example:

Public int findmin(int a, int b)

{

if a < b

  return a

else

 return b

}


You can call a function using the name of the process. The following example exemplifies this:

Public int findmin(int a, int b)

{

if a < b

  return a

else

 return b

}

Static void main(string[ ] args)

{int a = 5, b= 10

int result = findmin(a, b)

Console. WriteLine(“minimum value is” : result);

}


After learning about c# functions, we will move on to c# collections and their various classes, described in this c# basics article.

C# Collections

Collection classes are specialized data storage and retrieval classes. These classes support stacks, queues, lists, and hash tables. The interfaces of most collection classes are the same.

Collection classes serve various functions, such as dynamically allocating memory to elements and accessing a list of items via an index, among others. These classes construct collections of Object objects, which serve as the foundation for all data types in C#.

The System. Collection namespace's most used classes are listed below. To learn more about them, follow the table below:

Classes 

Description

ArrayList()

It represents an ordered collection of objects that can be individually indexed

HashTable()

It represents an ordered collection of objects that can be individually indexed.

SortedList()

To access the items in a list, it employs both a key and an index.

stack()

It represents a collection of objects arranged in a last-in, first-out order.

queue()

It represents a collection of objects arranged in a first-in, first-out order.

bitarray()

It represents a binary representation array with the values 1 and 0.

Now, in this c# article, we will attempt to understand c# enums through the use of an example for a better understanding.

C# Enum

An enum is a type of "class" "representing a collection of constants (variables that cannot be changed or read).

Use the enum keyword (rather than class or interface) to create an enum, and separate the enum items with a comma:

Example:

enum direction

{

  East;

  West;

  North;

  South;

}


Following this c# basics article, we will discuss one of the essential concepts in c#, object-oriented programming in c#.

C# OOPs

OOP is an abbreviation for Object-Oriented Programming. Procedural programming is all about writing procedures or methods that perform operations on data. In contrast, object-oriented programming is all about creating objects that contain both data and processes.

Object-oriented programming has several advantages over procedural programming, including the following:

  • OOP is faster and easier to implement.
  • OOP gives the programs a clear structure.
  • OOP aids in keeping C# code DRY (DoDon'tepeat Yourself) and makes it easier to maintain, modify, and debug.
  • OOP allows for the creation of fully reusable applications with less code and a shorter development time.

In C#, everything is associated with classes and objects and their attributes and methods. A car, for example, is an object in real life. The car has features like size and color and methods like start and stop. A Class functions similarly to an objective function or a "blueprint" "or creating objects.

Object


Attribute

Function 

A car


Size and color

Start and stop 

Let's overall four c# oops concepts in greater depth:

c#-oops-concept

Abstraction

  • "it" represents the essential feature without representing the background details ``''s the definition of abstraction.
  • Abstraction allows you to concentrate on what the object does rather than how it does it.
  • Abstraction offers you a generalized view of your classes or objects by providing relevant information.
  • Abstraction is concealing an object's working style while understandably displaying its information.

Encapsulation 

  • Encapsulation is combining a data member and a method into a single unit (or class).
  • Encapsulation is the process of enclosing something in a capsule. That is having the related operations and data related to an object into that object.

Inheritance 

  • In C#, fields and methods can be inherited from one class. For example, the "i" inheritance concept" "s divided into two categories:
  • Derived Class (child) - a class descended from another class.
  • The class inherited is known as the base class (parent).

Polymorphism 

  • Polymorphism in C# refers to the ability of objects of different types to provide a unique interface for other method implementations. 
  • It is commonly used in the context of late binding, in which the behavior of an object in responding to a call to its method members is determined at run time based on the object type.

C# polymorphism is off two types:

  • Compile Time Polymorphism 

When we create two or more methods with the same name but different parameters or a different series of parameters and the time of call, the compiler decides which way should be called based on the given arguments at the time of compilation.

That is why it is called compile-time polymorphism, also known as static polymorphism.

  • Runtime Polymorphism

When we create a method with the same name in an inherited class and want to override the functionality of the base class, The term polymorphism ``''refers to the fact that the compiler determines which methods should be called at runtime. This is accomplished by combining a virtual keyword with a method.

We create a virtual base class method, and an override derived class method to override the base class method.

In this c# basics article, we will see c# access modifier after understanding c# object oriented programming os oops concepts in c# programming language.

C# Access Specifier

In C#Access modifiers specify the scope of accessibility of a class member or type of the class itself. 

Public : The code is available to all classes.

Private : The code can only be accessed within the same class.

Protected : The code is available within the same class or in a class inherited from that class. 

Internal : The code is only accessible within its assembly and cannot be accessed from another community.

Following on from that c# article, we will now look at various types of file operations and their descriptions.

C# File Operations

The file mode enumerator defines various file opening methods. The following members of the file mode enumerators are described:

  • Append():  Appends text to the end of a file that already exists.
  • Copy():  Duplicates a file
  • Create(): Creates or replaces a file.
  • Delete(): Removes a file
  • Exists(): Checks to see if the file exists.
  • ReadAllText(): This function reads the contents of a file.
    • Replace(): It replaces the contents of one file with the contents of another.

  • WriteAllTexts():  Makes a new file and writes its contents to it.

This c# basics article will look at c# exception handling, which is the next step in the c# programming language.

C# Exception Handling

Exception handling is a phase that deals with handling errors and exceptions that occur during runtime due to coding errors or invalid user input.

In C#, we use four keywords in exception handling:

  • Try: The try statement allows you to define a block of code that will be tested for errors as it runs.
  • Catch: If any error occurs in the try block, the catch statement allows you to define a block of code that will be performed.
  • Finally: The final statement allows you to run code after trying and catching regardless of the outcome.
  • Throw: The throw statement allows you to define your error.

Last but not least, in the c# basics tutorial, we will see some new c# programming language features.

C# New Features

The new C# 8 features include:

  • Interface methods by default
  • Types of nullable references
  • Enhancements to pattern matching
  • Asynchronous streams
  • Making use of declarations
  • Interpolated verbatim string enhancement
  • Assignment of null-coalescing
  • Local static functions
  • Indices and their ranges
  • Types of unmanaged construction
  • In nested expressions, use Read-only-Member Stackable

Now that we've reached the end of this c# basics article let's summarize everything we've learned.

Master Java programming and elevate your career with the Java Certification Course by Simplilearn. Gain in-demand skills and become job-ready. Enroll now and transform your future!

Next Steps

First, in this article, we learned about the history of the c# programming language, followed by a brief introduction to c# programming. Finally, we looked at different types of comments and syntax in the c# programming language. We then looked at various kinds of variables, data types, and operators in C#. Then, in this c# basics article, we looked at the structure of the c# programming language and c# arrays, string functions, collections, and enums. Following that, we discussed oops concepts in the C# programming language and access specifiers, file operations, and exception handling. Finally, we saw some new features of the C# programming language.

If you would like to go beyond Mobile and Software Development and gain knowledge of the most in-demand programming languages and skills today, this is the path for you. Simplilearn's Full Stack Developer - MERN Stack are a good fit in that case. For more information, look into this well-known Bootcamp program.

Do you have any questions about this C# Basics tutorial? Please leave them in the comments area at the bottom of this page if you do. Our experts will be delighted to resolve your queries as earliest as possible!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.