× 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.

Understanding Namespace

  • Here’s a simple C# program that demonstrates the concept of namespaces by creating two namespaces, each containing a class with a method. One namespace's method calls the other namespace's method, helping to understand how namespaces work.
                        
using System;

namespace FirstNamespace
{
    // Class in the first namespace
    public class FirstClass
    {
        public void DisplayMessage()
        {
            Console.WriteLine("Hello from the First Namespace!");
        }
    }
}

namespace SecondNamespace
{
    // Class in the second namespace
    public class SecondClass
    {
        public void ShowMessage()
        {
            Console.WriteLine("Hello from the Second Namespace!");
        }

        // Method to call a method from FirstNamespace
        public void CallFirstNamespaceMethod()
        {
            FirstNamespace.FirstClass firstClassObj = new FirstNamespace.FirstClass();
            firstClassObj.DisplayMessage();
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating an object of the SecondClass
        SecondNamespace.SecondClass secondClassObj = new SecondNamespace.SecondClass();

        // Call method of SecondNamespace
        secondClassObj.ShowMessage();

        // Call method from FirstNamespace through SecondNamespace
        secondClassObj.CallFirstNamespaceMethod();

        Console.ReadLine(); // Keep the console open
    }
}
                        
                    

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
float temperature = 36.6f; // Float type for single-precision 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";
  • float: Represents single-precision floating-point numbers. A f suffix is required for float literals. Example: float temperature = 36.6f;
  • double: Represents double-precision floating-point numbers (numbers with decimal points). Example: double salary = 5000.50;
  • bool: Represents boolean values (true or false). Example: bool isEmployed = true;

Note: In C#, public methods and built-in method names (such as Console.WriteLine()) typically follow the PascalCase convention, where each word starts with a capital letter. However, not all function names are capitalized. Private or internal methods often follow the camelCase convention, where the first word starts with a lowercase letter and subsequent words are capitalized. This helps distinguish between public and private members in a class.

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!
                

Common String Operations

  • Concatenation

    Combining two or more strings. You can use the + operator or the String.Concat() method.

                                    string firstName = "John";
    string lastName = "Doe";
    string fullName = firstName + " " + lastName;  // John Doe
    // OR
    string fullName = String.Concat(firstName, " ", lastName);
                                
  • Substring

    Extracts a portion of the string based on starting position and length.

                                    string sentence = "Hello, World!";
    string sub = sentence.Substring(7, 5); // Output: World
                                
  • Length

    Returns the number of characters in the string.

                                    int length = fullName.Length;  // Output: 8 for "John Doe"
                                
  • String Interpolation

    Inserting variables inside a string using the $ symbol.

                                    string greeting = $"Hello, {firstName} {lastName}!";
                                
  • Uppercase / Lowercase Conversion

    Convert a string to uppercase or lowercase.

                                    string lower = fullName.ToLower();  // john doe
    string upper = fullName.ToUpper();  // JOHN DOE
                                
  • Replace

    Replaces occurrences of a specified character or substring.

                                    string replaced = fullName.Replace("Doe", "Smith");  // John Smith
                                
  • Split

    Splits a string into an array of substrings based on a delimiter.

                                    string names = "John,Doe,Jane";
    string[] nameArray = names.Split(',');  // ["John", "Doe", "Jane"]
                                
  • Trim

    Removes leading and trailing white spaces.

                                    string trimmed = "  Hello  ".Trim();  // Output: "Hello"
                                
  • Contains / StartsWith / EndsWith

    Checks for substring or how a string starts or ends.

                                    bool contains = fullName.Contains("John");   // true
    bool starts = fullName.StartsWith("John");   // true
    bool ends = fullName.EndsWith("Doe");        // true
                                
  • String Comparison

    Use Equals or CompareTo methods to compare two strings.

                                    bool areEqual = firstName.Equals("John");  // true
    int comparison = firstName.CompareTo(lastName);  // Negative value as "John" comes before "Doe"
                                

Working with Dates and Time

In C#, date and time are represented by the DateTime struct. It can store both date and time.

Date Input and Parsing in C#

When we input a date from the user in C#, we typically collect it as a string and then convert (parse) that string into a DateTime object. This is necessary because user input is always received as text, and we need to convert it into the appropriate data type for further operations.

Example of getting a date input:

                        Console.Write("Enter a date (yyyy-mm-dd): ");
string dateInput = Console.ReadLine();
                            

To convert a date string into a DateTime object, C# provides several methods for parsing. Parsing is the process of converting a string that represents a date into a structured DateTime object.

DateTime.Parse()

DateTime.Parse() is used to parse a string into a DateTime object. It assumes the string is formatted correctly, and if it is not, the program will throw an exception.

Example:

                        string dateInput = "2024-10-04";
DateTime parsedDate = DateTime.Parse(dateInput);
Console.WriteLine("Parsed Date: " + parsedDate.ToString("yyyy-MM-dd"));

In date formatting, "MM" and "mm" have different meanings in C# (and in most other date/time formatting systems):

  • MM (uppercase): Represents the month (from 01 to 12).
  • mm (lowercase): Represents the minute (from 00 to 59).

Important Considerations:

  • If the input format doesn’t match the expected date format, an exception is thrown.
  • Assumes the system’s current culture settings for interpreting date formats.

DateTime.TryParse()

DateTime.TryParse() is a safer alternative that attempts to parse the date and returns a boolean result indicating success or failure. It doesn’t throw an exception if the parsing fails, so it is ideal for user input scenarios.

Example:

                        string dateInput = "2024-10-04";
DateTime userDate;
bool isDateValid = DateTime.TryParse(dateInput, out userDate);

if (isDateValid)
{
    Console.WriteLine("Valid Date: " + userDate.ToString("yyyy-MM-dd"));
}
else
{
    Console.WriteLine("Invalid date format.");
}

Why Use TryParse:

  • It prevents the program from crashing if the input is not a valid date.
  • It returns true if the parsing is successful, and false otherwise, allowing you to handle errors gracefully.
  • It handles various date formats based on system culture settings (e.g., MM/dd/yyyy or dd/MM/yyyy).

How to Define a Date

                        DateTime now = DateTime.Now;  // Current date and time
DateTime specificDate = new DateTime(2023, 10, 4);  // Year, Month, Day

Common Date Operations

  • Formatting Dates

    You can format a date into different string representations.

                                    string formattedDate = now.ToString("MM/dd/yyyy");  // Output: 10/04/2024
                                
  • Adding or Subtracting Days, Months, or Years

    Methods like AddDays(), AddMonths(), and AddYears() are used for date arithmetic.

                                    DateTime futureDate = now.AddDays(5);  // Adds 5 days to current date
    DateTime pastDate = now.AddMonths(-2);  // Subtracts 2 months from current date
            
  • Comparing Dates

    Dates can be compared using comparison operators or the CompareTo method.

                                    if (now > specificDate) {
        // now is later than specificDate
    }
    
    int comparison = now.CompareTo(specificDate);  // 0: equal, 1: later, -1: earlier
            
  • Extracting Components

    You can retrieve the year, month, day, etc., from a DateTime object.

                                    int year = now.Year;  // Output: 2024
    int month = now.Month;  // Output: 10
    int day = now.Day;  // Output: 4
            
  • Difference Between Two Dates

    Use TimeSpan to calculate the difference between two dates.

                                    DateTime date1 = new DateTime(2024, 10, 1);
    DateTime date2 = new DateTime(2024, 10, 4);
    TimeSpan difference = date2 - date1;  // Output: 3 days
            
  • Parsing Strings into Dates

    Convert a string into a DateTime object using DateTime.Parse() or DateTime.TryParse().

                                    DateTime parsedDate = DateTime.Parse("2024-10-04");
                                
  • Getting Current Date Only

    You can use DateTime.Today to get the current date without the time component.

                                    DateTime today = DateTime.Today;  // Current date without time
                                

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
    float floatValue = Convert.ToSingle(strNum); // Converts string to float
    bool boolValue = Convert.ToBoolean("true"); // Converts string to boolean
    long longValue = Convert.ToInt64(strNum); // Converts string to long
    
    • Convert.ToInt32(): Converts a value to a 32-bit integer (int). Example: int num = Convert.ToInt32("123");
    • Convert.ToDouble(): Converts a value to a double-precision floating-point number (double). Example: double num = Convert.ToDouble("123.45");
    • Convert.ToSingle(): Converts a value to a single-precision floating-point number (float). Example: float num = Convert.ToSingle("123.45");
    • Convert.ToBoolean(): Converts a value to a Boolean (true or false). Example: bool flag = Convert.ToBoolean("true");
    • Convert.ToInt64(): Converts a value to a 64-bit integer (long). Example: long num = Convert.ToInt64("123456789");
    • Convert.ToDecimal(): Converts a value to a decimal for precise financial calculations. Example: decimal num = Convert.ToDecimal("123.45");
    • Convert.ToString(): Converts a value to a string. Example: string text = Convert.ToString(123);
    • Convert.ToDateTime(): Converts a value to a DateTime object. Example: DateTime date = Convert.ToDateTime("2024-01-01");
  • 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
                        

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
*/
    

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);
    }
                        

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.

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.

                        using System;

class Program
{
    static void Main()
    {
        // Output
        Console.WriteLine("Welcome to the C# program!");

        // Input
        Console.Write("Enter your favorite color: ");
        string color = Console.ReadLine();

        // Output with variable
        Console.WriteLine("Your favorite color is " + color + ".");
    }
}
                
                        using System;

class Program
{
    static void Main()
    {
        // Output
        Console.Write("Enter your birth year: ");
        string yearInput = Console.ReadLine();

        // Convert and calculate
        int birthYear = int.Parse(yearInput);
        int currentYear = DateTime.Now.Year;
        int age = currentYear - birthYear;

        // Output result
        Console.WriteLine("You are " + age + " years old.");
    }
}
                
                    using System;

class Program
{
    static void Main()
    {
        // Output message to prompt user for input
        Console.WriteLine("Enter the first number:");

        // Read the first number as a string and convert it to an integer
        string input1 = Console.ReadLine();
        int number1 = int.Parse(input1);

        // Output message to prompt user for the second number
        Console.WriteLine("Enter the second number:");

        // Read the second number as a string and convert it to an integer
        string input2 = Console.ReadLine();
        int number2 = int.Parse(input2);

        // Calculate the sum of the two numbers
        int sum = number1 + number2;

        // Output the result
        Console.WriteLine("The sum of {0} and {1} is {2}.", number1, number2, sum);
    }
}
                    

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.");
        }
    }
}