× back

C# Programming Language

Features of C# Programming Language:

  • Simple: C# offers a structured programming approach, making it easier for developers to write, read, and maintain code.
  • Modern Programming Language: C# is designed to meet the current trends in software development, making it versatile for building simple, scalable, and robust applications.
  • Object-Oriented: As an object-oriented programming language (OOP), C# supports features such as inheritance, polymorphism, encapsulation, and abstraction, which make code modular and reusable.
  • Type-Safe: C# ensures that type-safe code can only access memory locations that it has permission to execute, improving the security of programs.
  • Interoperability: Interoperability allows C# programs to interact with other programming languages or legacy systems, making it possible to call functions from native C++ applications or integrate with other technologies.
  • Scalable: C# is a scalable programming language. When updating an application, you can replace older components with new ones without affecting the rest of the program.
  • Component-Oriented: C# promotes the development of applications by combining reusable components, which improves maintainability and reduces development time.
  • Structured Programming Language: C# follows a structured programming approach that ensures the code is well-organized, improving readability and debugging efficiency.
  • Rich Standard Library: C# includes a vast library of pre-built classes and functions, known as the Base Class Library (BCL), which simplifies tasks such as file handling, data manipulation, and network communication.
  • Fast Performance: C# is known for its high performance, making it suitable for applications that require fast processing, such as real-time systems or games.

Syntax of C#

Understanding the basic syntax of C# is crucial for writing efficient code. Below are the main elements of C# syntax:

Structure of a C# Program

A simple C# program consists of several components:

        
using System; // Namespace declaration

namespace HelloWorldApp // Namespace definition
{
    class Program // Class declaration
    {
        static void Main(string[] args) // Main method (entry point of the program)
        {
            Console.WriteLine("Hello, World!"); // Output statement
        }
    }
}
        
    
  • using: Keyword used to include namespaces in the program.
  • namespace: Logical container for classes and other types. Helps organize code.
  • class: Defines the blueprint for creating objects. Every C# program has at least one class.
  • Main method: The entry point of the program where execution starts.
  • Console.WriteLine: Used to print output to the console.

Variables and Data Types

Variables are used to store data in a program. C# is a strongly-typed language, meaning you must declare the type of data a variable will hold. Each variable is associated with a specific data type that determines the kind of values it can store and what operations can be performed on them.

                        
// Examples of variable declarations in C#
int age = 25; // Integer type
string name = "John"; // String type
double salary = 5000.50; // Double type for floating-point numbers
bool isEmployed = true; // Boolean type (true or false)
                        
                    
  • int: Represents integer values (whole numbers). Example: int age = 25;
  • string: Represents sequences of characters (text). Example: string name = "John";
  • double: Represents floating-point numbers (numbers with decimal points). Example: double salary = 5000.50;
  • bool: Represents boolean values (true or false). Example: bool isEmployed = true;

Working with Strings

Strings in C# are sequences of characters used to represent text. You can manipulate strings using various methods provided by the string class.

                    
// Example of working with strings
string greeting = "Hello, World!";
string upperCaseGreeting = greeting.ToUpper(); // Converts string to uppercase
Console.WriteLine(upperCaseGreeting); // Output: HELLO, WORLD!
                    
                

Working with Dates and Time

In C#, the DateTime structure is used to represent dates and times. You can retrieve the current date and time, format dates, and perform date arithmetic.

                    
// Example of working with DateTime
DateTime currentDate = DateTime.Now; // Gets the current date and time
DateTime birthDate = new DateTime(1990, 5, 15); // Specifies a custom date
TimeSpan ageSpan = currentDate - birthDate; // Calculates the difference between two dates
int age = ageSpan.Days / 365; // Convert the difference to years
Console.WriteLine($"Your age is {age} years."); // Output: Your age is (calculated age) years
                    
                

Converting Between Data Types

Data type conversion allows transforming one data type into another. C# provides multiple ways to perform conversions, including implicit and explicit conversion, methods like Convert and Parse:

  • Implicit Conversion: Happens automatically when there’s no risk of data loss. For example, converting an int to a double can happen implicitly.
  •                         
    // Implicit conversion example
    int intNum = 10;
    double doubleNum = intNum; // No need for casting, happens automatically
                            
                        
  • Explicit Conversion (Casting): Required when there’s potential for data loss. For example, converting a double to an int requires explicit casting because you might lose the fractional part.
  •                         
    // Explicit conversion example
    double doubleNum = 10.5;
    int intNum = (int)doubleNum; // Cast explicitly, results in 10 (fractional part lost)
                            
                        
  • Using Methods: C# provides methods for conversions, such as Convert.ToInt32(), ToString(), and Parse().
  •                         
    // Example of using Convert methods
    string strNum = "123";
    int num = Convert.ToInt32(strNum); // Converts string to integer
    double doubleValue = Convert.ToDouble(strNum); // Converts string to double
                            
                        
  • Using Parse Method: The Parse() method converts a string representation of a number into a specific data type (e.g., int, double). This method throws an exception if the format is incorrect.
  •                         
    // Example of using Parse method
    string strNum = "456";
    int num = int.Parse(strNum); // Converts string to integer
    Console.WriteLine(num); // Output: 456
    
    string strDecimal = "123.45";
    double doubleValue = double.Parse(strDecimal); // Converts string to double
    Console.WriteLine(doubleValue); // Output: 123.45
                            
                        
  • TryParse Method: Unlike Parse(), TryParse() does not throw an exception. It returns a boolean value indicating whether the conversion was successful.
  •                         
    // Example of using TryParse method
    string strNum = "789";
    int result;
    bool isParsed = int.TryParse(strNum, out result); // Returns true if successful
    Console.WriteLine(isParsed ? $"Parsed: {result}" : "Failed to parse"); // Output: Parsed: 789
                            
                        

3. Comments

Comments are used to explain code and are ignored by the compiler. There are two types of comments in C#:

        
// This is a single-line comment

/*
This is a
multi-line comment
*/
        
    

4. Operators in C#

C# supports various operators for performing calculations and comparisons.

  • Arithmetic Operators: Used for basic arithmetic operations.
    • + (Addition)
    • - (Subtraction)
    • * (Multiplication)
    • / (Division)
    • % (Modulus)
  • Comparison Operators: Used for comparing values.
    • == (Equal to)
    • != (Not equal to)
    • > (Greater than)
    • < (Less than)
    • >= (Greater than or equal to)
    • <= (Less than or equal to)
  • Logical Operators: Used for logical operations.
    • && (Logical AND)
    • || (Logical OR)
    • ! (Logical NOT)

Control Statements in C#

Control statements are fundamental constructs in programming used to dictate the flow of execution based on certain conditions or to repeat blocks of code. Understanding these statements is crucial for developing effective and efficient code.

Conditional Statements

Conditional statements allow the program to execute different sections of code based on certain conditions.

  • if-else: Executes a block of code if a condition is true, and another block if the condition is false.
  •                         
    int age = 20;
    if (age > 18)
    {
        Console.WriteLine("You are an adult.");
    }
    else
    {
        Console.WriteLine("You are not an adult.");
    }
                            
                        
  • else if: Allows checking multiple conditions sequentially.
  •                         
    int score = 85;
    if (score >= 90)
    {
        Console.WriteLine("Grade: A");
    }
    else if (score >= 80)
    {
        Console.WriteLine("Grade: B");
    }
    else
    {
        Console.WriteLine("Grade: C");
    }
                            
                        
  • switch: Selects one of many code blocks to be executed based on the value of an expression.
  •                         
    int day = 3;
    switch (day)
    {
        case 1:
            Console.WriteLine("Monday");
            break;
        case 2:
            Console.WriteLine("Tuesday");
            break;
        case 3:
            Console.WriteLine("Wednesday");
            break;
        default:
            Console.WriteLine("Invalid day");
            break;
    }
                            
                        

Loops

Loops are used to execute a block of code repeatedly based on a condition or a specified number of iterations.

  • for loop: Executes a block of code a specific number of times, controlled by a loop variable.
  •                         
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine("Iteration: " + i);
    }
                            
                        
  • while loop: Repeats a block of code as long as a specified condition is true.
  •                         
    int i = 0;
    while (i < 5)
    {
        Console.WriteLine("Iteration: " + i);
        i++;
    }
                            
                        
  • do-while loop: Similar to the `while` loop, but guarantees that the block of code is executed at least once.
  •                         
    int i = 0;
    do
    {
        Console.WriteLine("Iteration: " + i);
        i++;
    }
    while (i < 5);
                            
                        
  • foreach loop: Iterates over a collection or array, executing a block of code for each item.
  •                     
    string[] names = { "Alice", "Bob", "Charlie" };
    foreach (string name in names)
    {
        Console.WriteLine("Name: " + name);
    }
                            
                        

6. Functions (Methods)

Functions are reusable blocks of code that perform a specific task.

        
void SayHello() // Function definition
{
    Console.WriteLine("Hello, World!");
}

SayHello(); // Function call
        
    
  • void: Indicates that the method does not return a value.
  • SayHello: The name of the function.
  • Function call: The function is executed when it's called.

7. Classes and Objects

Classes are blueprints for creating objects, and objects are instances of classes.

        
class Person // Class definition
{
    public string Name; // Field

    public void Greet() // Method
    {
        Console.WriteLine("Hello, my name is " + Name);
    }
}

Person person1 = new Person(); // Create object
person1.Name = "John"; // Assign value
person1.Greet(); // Call method
        
    

Basic Input and Output in C#

Input and output operations are fundamental to interacting with users and handling data in C# programs. Understanding these operations is crucial for developing applications that can receive input from users and display output effectively.

Output in C#

Output operations are used to display information to the user. The most common methods for outputting data in C# are `Console.WriteLine()`, `Console.Write()`, and `string.Format()`.

Input in C#

Input operations are used to receive data from the user. The primary method for reading input in C# is `Console.ReadLine()`, which reads a line of text from the console.

Practical Examples

Here are some basic examples demonstrating how to use these I/O methods in practice.

Arrays in C#

Arrays are a collection of items stored at contiguous memory locations. In C#, arrays are used to store multiple values of the same type in a single variable.

Declaring and Initializing Arrays

Before using arrays, you need to declare and initialize them. Here’s how:

  • Declaration: Specifies the type of elements and the array name.
  •                     
    int[] numbers; // Declares an array of integers
                        
                    
  • Initialization: Allocates memory for the array and assigns values.
  •                     
    numbers = new int[5]; // Initializes an array with 5 elements
    
    // Alternatively, you can declare and initialize in one line:
    int[] numbers = new int[] { 1, 2, 3, 4, 5 };
                        
                    
  • Accessing Array Elements: Use the index to access or modify elements.
  •                     
    int firstNumber = numbers[0]; // Accesses the first element
    numbers[1] = 10; // Modifies the second element
                        
                    

Looping Through Arrays

You can use loops to iterate through all elements of an array. The most common loop for this purpose is the for loop:

                
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
                
            

Types of Arrays

C# supports several types of arrays:

  • Single-Dimensional Arrays: The simplest type of array that stores data in a single line.
  •                     
    int[] singleDimArray = { 10, 20, 30, 40, 50 };
                        
                    
  • Multi-Dimensional Arrays: Arrays with more than one dimension. Typically used for matrices.
  •                     
    int[,] multiDimArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
                        
                    
  • Jagged Arrays: Arrays of arrays, where each sub-array can have different lengths.
  •                     
    int[][] jaggedArray = new int[3][];
    jaggedArray[0] = new int[] { 1, 2 };
    jaggedArray[1] = new int[] { 3, 4, 5 };
    jaggedArray[2] = new int[] { 6, 7, 8, 9 };
                        
                    

Advantages of Arrays

  • Efficient Memory Access: Arrays provide efficient access to elements using indices. Accessing an element is fast and requires constant time, O(1).
  • Contiguous Memory Allocation: Arrays are stored in contiguous memory locations, which improves cache performance and access speed.
  • Fixed Size: The fixed size of an array can simplify the memory management and make it easier to predict and manage the memory usage.
  • Simplicity: Arrays are straightforward and easy to use for storing and accessing multiple values of the same type.
  • Direct Access: Arrays provide direct access to elements via index, which makes it easier to manipulate and access data.

Disadvantages of Arrays

  • Fixed Size: Once an array is created, its size cannot be changed. This can lead to inefficient memory usage if the array is too large or if the number of elements exceeds the initial size.
  • Memory Waste: If an array is allocated with a size larger than needed, the extra memory allocated can be wasted, leading to inefficient memory usage.
  • Costly Resizing: To resize an array, a new array must be created and elements copied over, which can be costly in terms of performance and time.
  • Limited Flexibility: Arrays can only store elements of the same type and do not provide methods for dynamically changing their size or structure.
  • Index Out of Bounds: Accessing an element with an invalid index can lead to runtime errors, such as `IndexOutOfRangeException` in C#.

Basic Programs

Example 1: Sum of Array Elements

This program calculates the sum of all elements in an array.

                
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int sum = 0;

        foreach (int number in numbers)
        {
            sum += number;
        }

        Console.WriteLine("Sum of array elements: " + sum);
    }
}
                
            

Example 2: Searching for an Element

This program searches for a specific element in the array and prints its index.

                
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };
        int searchElement = 30;
        int index = -1;

        for (int i = 0; i < numbers.Length; i++)
        {
            if (numbers[i] == searchElement)
            {
                index = i;
                break;
            }
        }

        if (index != -1)
        {
            Console.WriteLine("Element found at index: " + index);
        }
        else
        {
            Console.WriteLine("Element not found.");
        }
    }
}