Introduction to C#
C# (pronounced “C-Sharp”) is a modern, object-oriented programming language developed by Microsoft in the early 2000s as part of its .NET framework. It was designed by Anders Hejlsberg and combines the power of C++ with the simplicity of Visual Basic. C# is widely used for developing a variety of applications, including desktop software, web applications, cloud-based services, and mobile apps using technologies like Xamarin.
C# supports strong type checking, garbage collection, and modern programming concepts like encapsulation, inheritance, and polymorphism, making it reliable and easy to maintain. Its syntax is similar to C, C++, and Java, so it’s familiar to many programmers. Today, C# is one of the most popular programming languages, known for its versatility, performance, and extensive library support for building robust, scalable, and secure applications.
History of C#
The history of C# started when Microsoft saw the need for a modern, flexible, and secure programming language to work with its .NET framework, which was aimed at making software development faster and more reliable. Anders Hejlsberg, who had also worked on Turbo Pascal and Delphi, led the creation of C#.
In 2000, Microsoft officially announced C# along with the first version of the .NET Framework. C# quickly gained popularity because it combined the familiar syntax of C and C++ with the simplicity of Visual Basic, making it easier for developers to learn and use. Over the years, C# has continuously improved with new versions introducing features like LINQ, async programming, and pattern matching, allowing developers to build web applications, desktop software, mobile apps, games using Unity, and even cloud services. Today, C# remains a powerful and versatile language trusted by millions of developers worldwide.
Features of C#
C# has many powerful features that make it a popular and modern programming language:
Simple and Easy to Use:
C# was designed to be simple and straightforward, with a clean and readable syntax that is similar to C, C++, and Java. This makes it easier for programmers familiar with these languages to learn C# quickly. The language removes complex and confusing features like multiple inheritance and pointers (except in unsafe code), making it safer and less error-prone.
Object-Oriented:
C# fully supports object-oriented programming (OOP) principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. These principles help developers organize code into reusable modules, making large programs easier to build, understand, and maintain. For example, you can create classes that represent real-world objects and reuse or extend them as needed.
Type Safe:
C# is a type-safe language, which means it strictly checks data types during compile time and runtime. This prevents operations that could lead to errors or security risks, like mixing incompatible data types or accessing memory directly. Type safety helps catch mistakes early and makes applications more reliable and secure.
Modern Language:
C# includes many modern programming features like properties (which make it easier to access class data), events (to handle actions like button clicks), indexers (to treat objects like arrays), and delegates (to pass methods as parameters). These features make coding more flexible, powerful, and efficient.
Automatic Garbage Collection:
In C#, memory management is handled automatically by the .NET runtime’s garbage collector. It automatically frees up memory used by objects that are no longer needed, so developers don’t have to manage memory manually like in C or C++. This reduces memory leaks and makes programs run more smoothly.
Rich Library Support:
C# comes with the .NET Framework or .NET Core libraries, which include thousands of pre-built classes and methods for performing common tasks like file input/output, database access, networking, web development, graphics, and more. This saves developers time because they don’t have to write code for these tasks from scratch.
Cross-Platform:
Originally, C# was used mostly for Windows applications, but now, with .NET Core and .NET 5/6/7, C# applications can run on Windows, Linux, and macOS. Tools like Xamarin also allow developers to build cross-platform mobile apps for Android and iOS using C#.
Scalable and Update-Friendly:
C# is well-suited for building large and complex applications that can grow over time. Its object-oriented structure, clear syntax, and modular approach make it easy to maintain and update software as new requirements come up. This makes C# popular for enterprise-level and long-term projects.
Component-Oriented:
C# supports component-oriented programming, which means developers can build applications as a collection of reusable, self-contained components or modules. This makes software easier to develop, test, and maintain. Components can also be reused in other projects, saving time and effort.
Interoperable:
C# can work with code written in other programming languages and interact with different technologies. For example, it can call native Windows APIs, use COM components, and interact with databases or web services built in other languages. This makes it flexible and suitable for integrating with existing systems.
Applications of C#
- Web Applications: Using ASP.NET and ASP.NET Core, C# powers the back end of modern web applications. Developers can create dynamic websites, RESTful APIs, and enterprise-level web systems that are scalable, secure, and high-performing. ASP.NET Core allows cross-platform deployment on Windows, Linux, and macOS.
- Mobile Applications: With Xamarin and .NET MAUI, C# enables cross-platform mobile development for Android and iOS using a single codebase. This approach saves time and effort by allowing developers to write one application and deploy it across multiple devices without rewriting the code for each platform.
- Game Development: C# is the primary language used in Unity, one of the world’s most popular game engines. It’s used to script game logic, control animations, manage physics, and build interactive elements in 2D, 3D, AR, and VR games. Unity with C# is widely used in both indie and AAA game development.
- Cloud-Based Applications: C# integrates seamlessly with Microsoft Azure, making it a powerful choice for building scalable cloud applications. Developers can build web services, microservices, serverless functions, and more. It’s commonly used in cloud-first strategies for businesses of all sizes.
- Enterprise Applications: C# is a popular language for enterprise software development due to its robustness, scalability, and integration with the .NET ecosystem. It’s often used to build systems like CRM, ERP, and inventory management tools for large organizations that require secure and maintainable solutions.
- Internet of Things (IoT): C# can be used for IoT development through platforms like .NET nanoFramework and Azure IoT Hub. It enables programming for embedded systems and connected devices, allowing developers to collect data, trigger actions, and control hardware in smart environments.
Structure of C#
using System; // Namespace
namespace MyProgram // Namespace Declaration
{
class Program // Class Declaration
{
static void Main(string[] args) // Main Method
{
Console.WriteLine("Hello, World!"); // Statement
}
}
}- Namespace Declaration:
A namespace in C# is like a container that holds related classes, interfaces, and other namespaces. It helps organize code and avoid naming conflicts between classes with the same name in large projects. For example, namespace myprogram means that all the code inside belongs to Myprogram and can be referred to by that name elsewhere in the project. The .NET framework also uses namespaces like System to provide built-in classes.
- Class Declaration: A class is the building block of a C# program. It defines a blueprint for creating objects and contains code in the form of methods, variables, and properties. Every C# program must have at least one class because C# is an object-oriented language. For example, class Program creates a class named Program where we can write our methods and statements.
- Main Method: The Main method is the entry point of every C# console application. When you run a C# program, the execution starts from the Main method. It is defined as static void Main(string[] args). Here, static means it belongs to the class itself (not an instance of it), void means it does not return any value, and string[] args is used to accept command-line arguments if needed.
- Statements and Expressions: Statements are the actual instructions written inside methods, like Main, that tell the computer what to do. For example, Console.WriteLine(“Hello, World!”); is a statement that prints text to the screen. Expressions can be parts of statements that perform calculations or operations. Together, they make up the body of the program and define its behavior.
- Comments: Comments are notes written in the code to explain what the code does. They are ignored by the compiler, so they don’t affect how the program runs. Comments help make the code easier to understand for yourself and others. In C#, you can write single-line comments using // and multi-line comments using /* */.
Compiling and Executing a C# Program
Start the Visual Studio IDE.
From the menu bar, choose File → New → Project.
Select Console Application.
Enter a name for your project and click the OK button.
This will create a new project in the Solution Explorer.
Write your code in the code editor.
Click the Run button or press the F5 key to execute the project.
A command prompt window will appear, showing the output.
Variables in C#
A variable is a name given to a storage location in memory where you can store data. Variables are used to hold values that your program can read and change during its execution.
In C# there are different types of variables with different keywords
- int (Integer):
The int data type is used to store whole numbers without decimal points. It is very common for counting values like age, number of students, or quantity. It can store numbers from –2,147,483,648 to 2,147,483,647. Declaration example:
int age = 25;
- float (Floating Point):
The float type is used to store decimal numbers with single precision, which means it can handle small decimal values like temperature or marks with fractions. Its range is approximately ±1.5 × 10^−45 to ±3.4 × 10^38. When you declare a float, you must add f at the end. Declaration example:
float temperature = 36.6f;
- double (Double Precision Floating Point):
The double type is used when you need larger or more precise decimal numbers. It is double-precision and suitable for values like prices, distances, or scientific calculations. Its range is approximately ±5.0 × 10^−324 to ±1.7 × 10^308. Declaration example:
double price = 1999.99;
- char (Character):
The char data type stores a single character like a letter, digit, or symbol. It must be inside single quotes. It stores Unicode characters from U+0000 to U+FFFF. It is used for values like grades or gender. Declaration example:
char grade = ‘A’;
- string (Text):
The string type stores a group of characters, so it can hold words, sentences, or whole paragraphs. It is enclosed in double quotes and has no fixed size limit, depending on system memory. Declaration example:
string name = “Basant”;
- bool (Boolean):
The bool type stores only two values: true or false. It is mainly used in conditions, loops, and decision-making in programs. For example, it can check if a student passed or if a machine is on or off. Declaration example:
bool isPassed = true;
- byte:
The byte type stores small whole numbers from 0 to 255. It uses only 1 byte of memory and is useful when you are sure the number will not be negative and stays small. It is commonly used for raw data, images, or data transfer. Declaration example:
byte level = 100;
Data Types Overview
| Type | Example | Range |
|---|
| int | int age = 25; | -2,147,483,648 to 2,147,483,647 |
| float | float temp = 36.6f; | ±1.5 × 10^−45 to ±3.4 × 10^38 |
| double | double price = 1999.99; | ±5.0 × 10^−324 to ±1.7 × 10^308 |
| char | char grade = 'A'; | Unicode (U+0000 to U+FFFF) |
| string | string name = "Basant"; | Depends on system memory |
| bool | bool isPassed = true; | true or false |
| byte | byte level = 100; | 0 to 255 |
Example:
using System;
namespace MyProgram
{
class Program
{
static void Main(string[] args)
{
int age = 25;
string city = "Kathmandu";
Console.WriteLine("Age: " + age);
Console.WriteLine("City: " + city);
}
}
}
Identifier in C#(C Sharp)
An identifier is the name given to elements in a C # program, such as variables, methods, classes, objects, functions, or namespaces. Identifiers allow you to refer to these elements in your code.
Examples of identifiers
name variable
CalculateSum method
Student class
Rules for naming identifiers in C Sharp
- Must start with a letter or an underscore, but not with a number. Example: myVariable is correct, but 1variable is not correct
- Can contain letters, digits, and underscores only. Example: ageOne is correct, but first-name is not correct because hyphens are not allowed
- They are case-sensitive. Example: Age and age are two different identifiers
- Cannot be a C # keyword. For example, you cannot name a variable class or int
- Should be meaningful It is good practice to use descriptive names like total marks instead of tm
Data Types in C#:
- In C#, a data type is a classification that specifies which type of value a variable can hold, how much memory it needs, and what operations can be performed on it. Data types define the nature of data, such as numbers, text, or logical values, and help the compiler allocate the appropriate memory space and handle the data correctly during program execution.
The most common data Types are described below:
- int: The int data type in C# stores whole numbers without decimals. It is commonly used for counting and basic calculations.
Example: int age = 20; — Here, the variable age stores the whole number 20.
- Float: The float type stores numbers with a fractional part (decimals) but with single precision. It is useful when you need to save memory and don’t need very high accuracy.
Example: float price = 19.99f; — The f at the end shows it’s a float.
- Double: The double type also stores decimal numbers but with double precision, making it more accurate than float. It is often used in scientific or engineering calculations.
Example: double distance = 12345.67; — This stores a distance value.
- char: The char type stores a single character like a letter, number, or symbol. It must be written inside single quotes.
Example: char grade = ‘A’; — This stores the letter A as a grade.
- bool: The bool type stores only true or false values. It is used for conditions and decisions in programs.
Example: bool isPassed = true; — This shows a student has passed.
- Byte: The byte type stores small numbers from 0 to 255 and is useful for working with binary data or files.
Example: byte level = 200; — This could store a game level or data byte.
- Short: The short type stores small whole numbers in a smaller range than int. It saves memory when the values are known to be small.
Example: short temperature = -5; — This stores a small temperature value.
- Long: The long type stores large whole numbers. It is used when int is not enough to hold the value.
Example: long population = 7896543210; — This could store a country’s population.
- Decimal: The decimal type is used for precise decimal numbers, especially in financial calculations to avoid rounding errors.
Example: decimal salary = 15200.50m; — The m shows it’s a decimal value.
- String: The string type stores text, which is a sequence of characters. It is very common for names, addresses, and messages.
Example: string name = “Alice”; — This stores the name Alice.
- Object: The object type can store any kind of data — numbers, strings, or custom types. It is the base type for all other data types.
Example: object data = 25; — Here, data stores an integer but could later hold other types too.
- Dynamic: The dynamic type lets you store any data type, and the actual type is determined at runtime. It is useful when you don’t know the exact type in advance.
Example: dynamic value = “Hello”; — value stores a string now, but you can assign a number later.
Type Casting in C#:
Type casting is the process of converting one data type into another. In C#, it is used when you need to store a value of one type into a variable of another type. There are two main types of type casting: Implicit Casting and Explicit Casting.
1. Implicit Casting (Automatic)
Implicit casting happens automatically when you convert a smaller type to a larger type — there is no data loss, so C# does it for you.
Example:
int num = 100;
double value = num; // int to double (automatic)
2. Explicit Casting (Manual)
Explicit casting must be done manually when you convert a larger type to a smaller type — because there is a risk of data loss. You use parentheses to tell the compiler to do this conversion.
Example:
double salary = 12345.67;
int wholeSalary = (int) salary; // double to int (decimal part is lost)
C# program that shows both implicit and explicit type casting in action:
using System;
class TypeCastingExample
{
static void Main()
{
// Implicit Casting (Automatic)
int num = 50;
double doubleNum = num; // int automatically converted to double
Console.WriteLine("Implicit Casting:");
Console.WriteLine("Integer value: " + num);
Console.WriteLine("Converted to double: " + doubleNum);
Console.WriteLine(); // Blank line for clarity
// Explicit Casting (Manual)
double salary = 12345.67;
int wholeSalary = (int)salary; // double manually converted to int
Console.WriteLine("Explicit Casting:");
Console.WriteLine("Double value: " + salary);
Console.WriteLine("Converted to int (decimal removed): " + wholeSalary);
Console.WriteLine(); // Blank line for clarity
// Using Convert Class
string strNumber = "100";
int parsedNumber = Convert.ToInt32(strNumber);
Console.WriteLine("Using Convert:");
Console.WriteLine("String value: " + strNumber);
Console.WriteLine("Converted to int: " + parsedNumber);
}
}User Input in C#:
In C#, you can read user input from the keyboard using the Console.ReadLine() method. By default, it reads the input as a string, so if you want to work with numbers, you need to convert the input to the desired type (like int or double).
Example Program: Taking User Input
using System;
class UserInputExample
{
static void Main()
{
// Take a string input
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
// Take an integer input
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = Convert.ToInt32(ageInput);
Console.WriteLine("You are " + age + " years old.");
// Take a double input
Console.Write("Enter your salary: ");
double salary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Your salary is: " + salary);
}
}# program to add two numbers entered by the user:
using System;
class AddTwoNumbers
{
static void Main()
{
// Ask the user to enter the first number
Console.Write("Enter the first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
// Ask the user to enter the second number
Console.Write("Enter the second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
// Add the two numbers
int sum = num1 + num2;
// Display the result
Console.WriteLine("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
}Operator in C#:
In C#, an operator is a special symbol that performs an operation on one, two, or more operands (variables or values) and produces a result. Operators are used to perform calculations, compare values, assign values, and perform logical operations in a program.
Types of Operators in C#:
Operators in C# are mainly divided into the following types:
- Arithmetic Operators:
These operators are used to perform basic mathematical operations like addition, subtraction, multiplication, division, and finding the remainder. Examples: + (Addition), – (Subtraction), * (Multiplication), / (Division), % (Modulus).
Example: