What is C#?

Posted in /  

What is C#?
paritoshlouhan

Paritosh Louhan
Last updated on December 21, 2024

    C# is a general-purpose and object-oriented programming language developed by Microsoft. It is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.

    Features of C#

    Below are some of the features of C# that make it a widely-used programming language in the software industry:

    • Follows the object-oriented programming paradigm.
    • Structured language.
    • Typesafe.
    • Scalable.
    • Component-oriented.
    • Asynchronous programming.
    • Speedy execution

    In this article, we will discuss basic concepts related to C#, what is C# used for, and how you can use it in accomplishing major tasks while developing software.

    Environment

    C# is a part of the .NET initiative, and thus, it requires the .NET framework for its execution. .NET is a platform for building and deploying web and desktop applications. Besides C sharp, the framework also supports other programming languages like Visual Basic and C++. C# consists of 2 main components:

    1. Common Language Runtime (CLR) : The .NET framework contains a run-time environment known as CLR, which runs the codes. It provides services to make the development process efficient.
    2. Framework Class Library (FCL) : It is a library of classes, value types, and interfaces that provide access to system functionality.

    The most popular IDE for developing applications using C# is Visual Studio. Since the .NET framework is only available for Windows, to run C# code on Linux or macOS, you will need Mono , which is an open-source version of the .NET framework that facilitates cross-platform development of .NET applications.

    Program Structure

    The extension of C# source code files is ‘. cs ’. It is a case-sensitive language, and all the statements and expressions must end with a semicolon (;). Let’s write a basic Hello World program and understand each part of the code step by step.

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    Console.WriteLine("Hello World");
    Console.ReadKey();
    }
    }
    }

    Output

    Hello World

    The first line imports the System namespace, which contains fundamental and base classes that define commonly-used values and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. So, the namespace is basically the collection of multiple classes.

    Our “HelloWorldApplication” namespace contains the “HelloWorld” class. We can import this namespace in some other file and use its methods and classes there. The Main method is the entry point of all C# programs. Methods are just the functions used in classes.

    • The Console.WriteLine() method of the System namespace displays the message on the console screen.
    • The Console.ReadKey() method waits for some key to be pressed and then exits the console. This avoids immediate stopping of the console application after running.

    Syntax of C#

    As C# is an object-oriented programming language, we write our code in the form of objects and classes. An object is a single entity that has several variables and methods associated with it. The class is a blueprint of objects.

    To understand it, let’s take an example of yourself. You are an object who belongs to the human class. The variables associated with you are hands, eyes, legs, etc. You can perform several actions like walking, jumping, and running, which are methods associated with the human class. Using the object-oriented approach makes the code better readable and easier to debug and refactor.

    Let’s create a class ‘Human’ and write different methods in it to demonstrate the syntax of C#.

    using System;
    namespace Application {
    class Human{public void Walk() {
    Console.WriteLine("You are walking");
    }
    public void Run() {
    Console.WriteLine("You are running");
    }
    }
    class Execute {
    static void Main() {
    Human you = new Human();
    you.Walk();
    you.Run();
    Console.ReadLine();
    }
    }
    }

    Output:

    You are walking
    You are running

    We implemented two methods, namely ‘Walk’ and ‘Run’, for an object. Objects are created using new in C#. The void return type of function means it returns nothing. We will see more return types when we discuss data types in C#.

    Comments in C#

    Comments are the block of codes that are ignored by the compiler or the interpreter. They are used to make the code clear for some other person to understand and describe what the specific part of the code does. Single-line comments can be made using // and multiline with /* and */.

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    Console.WriteLine("I will execute");
    //I won't get executed
    Console.WriteLine("I will execute");
    /*
    I won't
    get executed
    as well
    */
    Console.ReadKey();
    }
    }
    }

    Output:

    I will execute
    I will execute

    Data Types in C#

    Variables are classified into value types, pointer types, and reference types in C#.

    • Value Type

    These types of variables can be assigned a value directly. They contain data like integers, floating-point numbers, and alphabets in their own memory space. Following are the common value types that are used in C#:

    Type Denotes Range
    bool Boolean value True or False
    byte 8-bit unsigned integer 0 to 255
    char 16-bit Unicode character U +0000 to U +ffff
    double 64-bit double-precision floating-point type (+/-)5.0 x 10-324 to (+/-)1.7 x 10308
    int 32-bit signed integer value -2,147,483,648 to 2,147,483,647
    float 32-bit single-precision floating-point type -3.4 x 1038 to + 3.4 x 1038
    • Reference Type

    Reference types store the reference of another variable's memory location in them. When we pass these variables into a method, the reference of that variable gets passed into that method instead of the copy of the variable. Therefore, if we modify the variable in the method, changes will be reflected in the original variable. Below are the common reference types in C#:

    • Arrays
    • Strings
    • Objects
    • We will discuss each of them later in this article.
    • Pointer Type

    Pointer-type variables store the memory address of another type. Below is the syntax for declaring the pointer:

    type* identifier;

    Variable and Constants in C#Please note that the type of pointer should be the same as the type of variable whose address this pointer is storing.

    • Variables

    A variable is nothing but a name given to a memory location. The memory occupied depends on the type of variable. The data inside a variable can change from time to time. It is not ‘ constant ’. The syntax for defining a variable is:

    type name_of_variable

    Let’s write a code to display the value of a variable and change it later on:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int a = 5;
    Console.WriteLine(a);
    a = 7;
    Console.WriteLine(a);
    Console.ReadKey();
    }
    }
    }

    Output:

    5
    7

    As you can see, the value of the variable has changed from 5 to 7.

    • Constants

    As the name suggests, their values can never be altered. Examples of constants are real numbers and characters. We can also create a memory location and assign it a constant value as shown below:

    const <data_type> <constant_name> = value;

    The following code will throw an error since we are trying to modify a constant value:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    const int a = 5;
    Console.WriteLine(a);
    a = 7;
    Console.ReadKey();
    }
    }
    }

    Input/Output in C#

    It's obvious that in many cases, you will need to read input from the user and print the result on the console after performing operations on the input. Let’s see how you can read the input and also print something on the console.

    The input can be taken using the Console.ReadLine() method in C# and printed using the Console.WriteLine() method. The Console.WriteLine() method applies a line break after printing the result. Please note that the Console.ReadLine() method initially takes input as a string .

    To read integer input, we can explicitly convert the string value into an integer using the Convert.ToInt32() method.

    Let’s read input from the user and print the user input on the console.

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    string a = Console.ReadLine();Console.WriteLine("Result is");
    Console.WriteLine(a);
    Console.ReadKey();
    }
    }
    }

    Output:

    hello
    Result is
    hello

    C# Operators

    Operators are useful for performing mathematical operations and comparisons on the operands. Operators can be unary, binary, or ternary. Unary operators work on a single operand, binary on 2 operands, and ternary on 3 operands. Let’s discuss each one of them one by one:

    1. Arithmetic Operators

    They are used to perform mathematical operations on operands. Use the table below to understand the working of each arithmetic operator:

    Operator Task Demonstration
    + Adds two operands. A + B
    - Subtracts second operand from first. A - B
    * Multiply two operands. A * B
    / Divide numerator by denominator. A / B
    % Gives the remainder when the numerator is divided by the denominator. A % B
    ++ Increments an integer by 1. A++
    -- Decrements an integer by 1. A--

    2. Relational Operators

    Relational operators are used to define relations between two operands. They are often used in decision-making in programming languages.

    Let’s look at different relational operators and how to use them in the table below:

    Operator Task Demonstration
    == Checks if the values of two operands are equal or not. If they are, the condition becomes true; otherwise, false. A == B
    != Checks if the values of two operands are equal or not. If they are equal, the condition becomes false; otherwise, true. A != B
    > Checks if the value of the left operand is strictly greater than the right operand. A > B
    < Checks if the value of the right operand is strictly greater than the left operand. A < B
    >= Checks if the value of the left operand is greater than or equal to the right operand. A >= B
    <= Checks if the value of the right operand is greater than or equal to the left operand. A <= B

    3. Logical Operators

    Logical operators are used to determine logic between two or more expressions. They always result in a single value. If you are familiar with logic gates, then you need no effort in understanding logical operators.

    For more insight, look at the following table. If A holds a boolean value of true and B holds a boolean value of false, then:

    Operator Task Demonstration
    || (OR) It results in a true value if either of the expression or operand is true. A || B = true
    && (AND) It results in a true value if both of the expressions or operands are true. A && B = false
    ! (NOT) It inverts the boolean value of the result. !(A && B) = true
    ^ (XOR) Results are true if and only if the two operands are different. A ^ B = true

    4. Bitwise Operators

    These operate on a single bit. We can use these types of operators on the bool data type that we discussed above. What if we do a bitwise operation of two numbers? Every number can be represented in the form of binary digits; 0 and 1.

    For instance, assume A is 2, B is 5, then the binary representation of these values are: 2: 0010 5: 0101. If we do bitwise OR of these two values, then this operation will be performed on each bit one by one, and the result will be 7 (0111) .

    Operator Task Demonstration
    & (AND) Results in 1 if and only if both bits are 1. A & B = 0 (0000)
    | (OR) Results 1 if either of the bits is 1. A | B = 7 (0111)
    ^ (XOR) Results in 1 if and only if both bits are different. A ^ B = 7 (0111)
    ~ It is a unary operator that flips the bit. ~A = -3
    << Left shifts all the bits by the specified value. A<<2 = 8 (1000)
    >> Right shifts all the bits by the specified value. A >> 2 = 0 (0000)

    5. Assignment Operators

    They are used to assign or modify a variable with a new value.

    Let’s see a few common assignment operators in C#:

    Operator Task Demonstration
    = Simply assign the right side operand value to the left side operand. A = B
    += Add the right side operand value into the left side operand and modify the left side operand. A=2 A+=2 A becomes 4
    -= Subtract the right side operand value from the left side operand and modify the left side operand. A=2 A-=2 A becomes 0

    Decision-Making

    It involves the conditional execution of the code. Before running a block of code, the program first checks some conditions and, if it is true, then executes the respective code. C# provides various conditional statements.

    Let’s discuss them in detail.

    1. If/else

    The syntax for if/else is:

    if(condition){
    // if condition succeeds, do this
    }
    else{
    // do this
    }

    if(condition1){A condition is checked in the if statement, and the respective code is executed if and only if the condition is true. We can also check more than 2 conditions by using else if together.

    Let’s see the syntax for the same:

    // if condition1 succeeds, do this
    }
    else if(condition2){
    // if the above condition fails and condition2 succeeds, do this
    }
    else{
    // If all above conditions fail, finally do this
    }

    using System;

    The working of the above code can be easily understood using the comments. Next, let’s see an example to understand the use of the above concepts.

    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int a=100;
    if(a<100){
    Console.WriteLine("Smaller than 100");
    }
    else if(a>=100){
    Console.WriteLine("Greater than or equal to 100");
    }
    else{
    Console.WriteLine("Not an integer");
    }
    Console.ReadKey();
    }
    }
    }

    Output:

    Greater than or equal to 100

    2. Switch Statement

    A switch statement tests a value against a set of cases and executes the block of code associated with the satisfied case. If none of them gets satisfied, the ‘ default’ case gets executed. Each case must end with a ‘ break’ statement. You will study the break statement in the ‘Loops’ topic of this article. The syntax for switch-case statements is:

    switch(expression) {
    case value1 :
    statements;
    break;
    case value2 :
    statements;
    break;
    default :
    statements;
    }

    Let’s look at an example to understand the flow of execution of switch statements:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int a=100;
    switch(a){
    case 100: //if a is 100
    Console.WriteLine("It is 100");
    break;
    case 10: //if a is 10
    Console.WriteLine("It is not 100");
    break;
    default:
    Console.WriteLine("It is not an integer");
    break;
    }Console.ReadKey();
    }
    }
    }

    Output:

    It is 100

    Loops in C#

    Loops are simply used to run the same kind of code multiple times. It is obviously better to write loop statements instead of writing the same thing thousands of times by yourself. There are basically 3 types of loops available in C#:

    1. for Loop

    The syntax is:

    for(initialize; condition; increment/decrement){
    statements
    }

    It initializes a value and increments/decrements it by some constant and runs until the condition is satisfied. Let’s look at an example to understand it well:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int i;
    for(i=1;i<=5;i++){
    Console.WriteLine(i);
    }Console.ReadKey();
    }
    }
    }

    Output:

    1
    2
    3
    4
    5

    2. while Loop

    It only checks the condition and runs the loop until the condition is satisfied. We need to initialize and increment/decrement the variables explicitly. The syntax is:

    initialize
    while(condition){increment/decrement}

    Try creating an example code for the "while" loop on your own and test it for various conditions!

    3. do/while loop

    It is quite similar to the while loop, except that it runs the block of code at least once .

    Let’s look at an example to understand the working of do/while:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int i=0;
    do{
    Console.WriteLine("Hello world");
    } while(i>0);
    Console.ReadKey();
    }
    }
    }

    Output:

    Hello world

    As you can see, the statement inside ‘ do’ got executed only once, and the condition inside ‘ while’ was never satisfied.

    Loop Control Statements

    These statements are useful to control the loop in a way that they can change the default behavior of the loop. There are 2 loop control statements, namely ‘ break ’ and ‘ continue ’.

    1. break

    If we wish to interrupt the running of a loop in between, we can use ‘break’ for it. For instance, if some condition is satisfied and you do not wish to run the loop further and consume more time, you can apply a ‘break’ statement inside the ‘ if’ condition. It will ignore all further activities related to the loop and jumps directly outside the loop block. The below example will break the loop as soon as it encounters 4:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int i;
    for(i=0;i<=5;i++){
    if(i==4){
    break;
    }
    Console.WriteLine(i);
    }
    Console.ReadKey();
    }
    }
    }

    Output:

    0
    1
    2
    3

    2. continue

    This statement does not break the loop but ignores all the code after it (inside the loop block) and starts the next iteration. For instance, while printing numbers from 1 to 5, if you wish to print all numbers other than 2, then you can go to the next iteration when the code encounters 2 and ignore further print statements while performing an iteration. See the following example:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int i;
    for(i=0;i<=5;i++){
    if(i==2){
    continue;
    }
    Console.WriteLine(i);
    }
    Console.ReadKey();
    }
    }
    }

    Output

    0
    1
    3
    4
    5

    Arrays in C#

    An array is a collection of multiple variables that store data in contiguous memory locations. They store the same type of data that can be accessed by using indexing. The indexing of an array starts from 0 and goes up to n -1, where n is the size of the array. Following is a common way to define and initialize an array in C#:

    int [] arr = new int[5] { 1, 2, 3, 4, 5};

    Another way to define and initialize an array in C# is:

    int[] arr = { 23, 45, 3};

    You can access an element of an array using [] after the array name. Using the following code in the ‘ Main’ method prints 1 in the console:

    Console.WriteLine(arr[0]);

    To iterate through the array elements, you can use the for loop that we discussed earlier. Let’s see an example to print all the elements of the array:

    using System;
    namespace HelloWorldApplication {
    class HelloWorld {
    static void Main() {
    int [] arr = new int[5] {1,2,3,4,5};
    for(int i=0; i<5;i++){
    Console.WriteLine(arr[i]);
    }
    Console.ReadKey();
    }
    }
    }

    Output:

    1
    2
    3
    4
    5

    Strings in C#

    Strings are objects whose values are in the form of text. They are similar to arrays and contain characters instead of integers. There are several ways to define a string in C#: See below:

    string str = "Hello"
    char[] characters = { 'A', 'B', 'C' };
    string str = new string(characters);

    The indexing and looping on strings can be performed similarly to arrays. Unlike arrays, strings are immutable , i.e., the values inside strings cannot be changed once initialized.

    Conclusion

    In this article, we discussed the basic concepts of the C# programming language. C# is a very powerful language that allows you to write codes securely and efficiently. It provides a large number of utilities and data structures that help you in software development.

    People are also reading:

    FAQs


    C# is a general-purpose programming language used for developing a variety of applications, such as mobile applications, desktop applications, enterprise applications, games, websites, and cloud-based services.

    Yes, C# is easy to learn because of its well-defined class hierarchy. It is an object-oriented programming language easier to learn than C and C++.

    You need to learn the .NET framework and any supported IDE (Integrated Development Environment) to get started with C#.

    .NET is an open-source developer platform developed by Mcirosoft for building a variety of applications. This platform primarily supports C#, VB.NET, and F# programming languages.

    Leave a Comment on this Post

    0 Comments