C#

 

  • C# (pronounced as "C sharp") is a modern, versatile, and object-oriented programming language developed by Microsoft.
  •  It was introduced in the early 2000s as part of the Microsoft .NET initiative and has since become a popular choice for developing a wide range of applications, including Windows applications, web applications, games, and more.

C# | Identifiers


In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. 
Example: 
 

public class GFG {
    static public void Main () 
    {
          int x;
    }
}

Here the total number of identifiers present in the above example is 3 and the names of these identifiers are: 
 

  • GFG: Name of the class
  • Main: Method name
  • x: Variable name

Rules for defining identifiers in C#:
There are certain valid rules for defining a valid C# identifier. These rules should be followed, otherwise, we will get a compile-time error. 
 

  • The only allowed characters for identifiers are all alphanumeric characters([A-Z][a-z][0-9]), ‘_‘ (underscore). For example “geek@” is not a valid C# identifier as it contain ‘@’ – special character.
  • Identifiers should not start with digits([0-9]). For example “123geeks” is not valid in the C# identifier.
  • Identifiers should not contain white spaces.
     
  • Identifiers are not allowed to use as keywords unless they include @ as a prefix. For example, @as is a valid identifier, but “as” is not because it is a keyword.
  • C# identifiers allow Unicode Characters.
  • C# identifiers are case-sensitive.
  • C# identifiers cannot contain more than 512 characters.
  • Identifiers do not contain two consecutive underscores in their name because such types of identifiers are used for the implementation.

Example:
 

// Simple C# program to illustrate identifiers
using System;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // variable
        int a = 10;
        int b = 39;
        int c;
 
        // simple addition
        c = a + b;
        Console.WriteLine("The sum of two number is: {0}", c);
    }
}

Output: 
 

The sum of two number is: 49

Below table shows the identifiers and keywords present in the above example:
 

KeywordsIdentifiers
usingGFG
publicMain
statica
voidb
intc

C# | Data Types

Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.

Data types in C# is mainly divided into three categories

  • Value Data Types
  • Reference Data Types
  • Pointer Data Type
  1. Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following are different Value Data Types in C# programming language :
    • Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.

      AliasType NameTypeSize(bits)RangeDefault Value
      sbyteSystem.Sbytesigned integer8-128 to 1270
      shortSystem.Int16signed integer16-32768 to 327670
      IntSystem.Int32signed integer32-231 to 231-10
      longSystem.Int64signed integer64-263 to 263-10L
      byteSystem.byteunsigned integer80 to 2550
      ushortSystem.UInt16unsigned integer160 to 655350
      uintSystem.UInt32unsigned integer320 to 2320
      ulongSystem.UInt64unsigned integer640 to 2630
    • Floating Point Types :There are 2 floating point data types which contain the decimal point.

      • Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.
      • Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.
      AliasType nameSize(bits)Range (aprox)Default Value
      floatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0F
      doubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0D
    • Decimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.
      AliasType nameSize(bits)Range (aprox)Default value
      decimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0M
    • Character Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.
      AliasType nameSize In(Bits)RangeDefault value
      charSystem.Char16U +0000 to U +ffff‘\0’
    • Example :

      // C# program to demonstrate 
      // the above data types
      using System;
      namespace ValueTypeTest {
            
      class GeeksforGeeks {
            
          // Main function
          static void Main()
          {
                
              // declaring character
              char a = 'G';
        
              // Integer data type is generally
              // used for numeric values
              int i = 89;
        
              short s = 56;
                
              // this will give error as number
              // is larger than short range
              // short s1 = 87878787878;
        
              // long uses Integer values which 
              // may signed or unsigned
              long l = 4564;
        
              // UInt data type is generally
              // used for unsigned integer values
              uint ui = 95;
        
              ushort us = 76;
              // this will give error as number is
              // larger than short range
        
              // ulong data type is generally
              // used for unsigned integer values
              ulong ul = 3624573;
        
              // by default fraction value
              // is double in C#
              double d = 8.358674532;
        
              // for float use 'f' as suffix
              float f = 3.7330645f;
        
              // for float use 'm' as suffix
              decimal dec = 389.5m;
        
              Console.WriteLine("char: " + a);
              Console.WriteLine("integer: " + i);
              Console.WriteLine("short: " + s);
              Console.WriteLine("long: " + l);
              Console.WriteLine("float: " + f);
              Console.WriteLine("double: " + d);
              Console.WriteLine("decimal: " + dec);
              Console.WriteLine("Unsinged integer: " + ui);
              Console.WriteLine("Unsinged short: " + us);
              Console.WriteLine("Unsinged long: " + ul);
          }
      }
      }

      Output :

      char: G
      integer: 89
      short: 56
      long: 4564
      float: 3.733064
      double: 8.358674532
      decimal: 389.5
      Unsinged integer: 95
      Unsinged short: 76
      Unsinged long: 3624573
      

      Example :

      // C# program to demonstrate the Sbyte
      // signed integral data type
      using System;
      namespace ValueTypeTest {
        
      class GeeksforGeeks {
        
          // Main function
          static void Main()
          {
              sbyte a = 126;
        
              // sbyte is 8 bit 
              // singned value
              Console.WriteLine(a);
        
              a++;
              Console.WriteLine(a);
        
              // It overflows here because
              // byte can hold values 
              // from -128 to 127
              a++;
              Console.WriteLine(a);
        
              // Looping back within 
              // the range
              a++;
              Console.WriteLine(a);
          }
      }
      }

      Output :

      126
      127
      -128
      -127
      

      Example :

      // C# program to demonstrate 
      // the byte data type
      using System;
      namespace ValueTypeTest {
        
      class GeeksforGeeks {
            
          // Main function
          static void Main()
          {
              byte a = 0;
        
              // byte is 8 bit 
              // unsigned value
              Console.WriteLine(a);
        
              a++;
              Console.WriteLine(a);
        
              a = 254;
                
              // It overflows here because
              // byte can hold values from
              // 0 to 255
              a++;
              Console.WriteLine(a);
        
              // Looping back within the range
              a++;
              Console.WriteLine(a);
          }
      }
      }

      Output :

      0
      1
      255
      0
      
    • Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.
      AliasType nameValues
      boolSystem.BooleanTrue / False

      Example :

      // C# program to demonstrate the
      // boolean data type
      using System;
      namespace ValueTypeTest {
            
          class GeeksforGeeks {
                
          // Main function
          static void Main() 
          {
                
              // boolean data type
              bool b = true;     
              if (b == true)
                  Console.WriteLine("Hi Geek");
          
      }
      }

      Output :

      Hi Geek
      
  2. Reference Data Types : The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object.
    • String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.
      Example :
      string s1 = "hello"; // creating through string keyword  
      String s2 = "welcome"; // creating through String class  
      
    • Object : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object.
    • Example :

      // C# program to demonstrate 
      // the Reference data types
      using System;
      namespace ValueTypeTest {
            
      class GeeksforGeeks {
            
          // Main Function
          static void Main() 
          {
                
              // declaring string
              string a = "Geeks"
                
              //append in a
              a+="for";
              a = a+"Geeks"
              Console.WriteLine(a);
                
              // declare object obj
              object obj;
              obj = 20;
              Console.WriteLine(obj);
                
              // to show type of object
              // using GetType()
              Console.WriteLine(obj.GetType()); 
          
      }
      }

      Output :

      GeeksforGeeks
      20
      System.Int32
      
  3. Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.
    To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
    ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.
    asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
    Syntax :
    type* identifier;
    

    Example :

    int* p1, p;   // Valid syntax
    int *p1, *p;   // Invalid 
    

    Example :

    // Note: This program will not work on
    // online compiler
    // Error: Unsafe code requires the `unsafe' 
    // command line option to be specified
    // For its solution:
    // Go to your project properties page and
    // check under Build the checkbox Allow
    // unsafe code.
    using System;
    namespace Pointerprogram {
          
    class GFG {
      
        // Main function
        static void Main()
        {
            unsafe
            {
                  
                // declare variable
                int n = 10;
                  
                // store variable n address 
                // location in pointer variable p
                int* p = &n;
                Console.WriteLine("Value :{0}", n);
                Console.WriteLine("Address :{0}", (int)p);
            }
        }
    }
    }

C# | Variables

A typical program uses various values that may change during its execution. For example, a program that performs some operations on the values entered by the user. The values entered by one user may differ from those entered by another user. Hence this makes it necessary to use variables as another user may not use the same values. When a user enters a new value that will be used in the process of operation, can store temporarily in the Random Access Memory of computer and these values in this part of memory vary throughout the execution and hence another term for this came which is known as Variables. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information.

Syntax:

type variable_name = value; 
or
type variable_names;

Example:

char var = 'h'; // Declaring and Initializing character variable
int a, b, c; // Declaring variables a, b and c of int type

Characteristics of Variables:

  • name : It must be a valid identifier. In above example, var is a valid identifier.
  • type : It defines the types of information which is to be stored into the variable. In above example char is a type.
  • value : It is the actual data which is to be stored in the variable. In above example ‘h’ is the value.

Rules for Naming Variables

  • Variable names can contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
  • The name of the variables cannot be started with a digit.
  • The name of the variable cannot be any C# keyword say int, float, null, String, etc.

Examples:

  • Valid Variables Names
    int age;
    
    float _studentname;
  • Invalid Variables Names
    int if; // "if" is a keyword
    
    float 12studentname; // Cannot start with digit
    

Defining or Declaring a Variable

There are some rules that must be followed while declaring variables :

  • specify its type (such as int)
  • specify its name (such as age)
  • Can provide initial value(such as 17)

Example :

int geeks;
float interest;

Initializing Variables

The term initializing means to assign some value to the variable. Basically, the actual use of variables comes under the initialization part. In C# each data type has some default value which is used when there is no explicitly set value for a given variable. Initialization can be done separately or may be with declaration.

Example :

int y = 7; // Declaring and initializing the variable at same time
int x; // Declaring variable x
x = 5; // initializing x with value 5

Two Ways for Initialization:

  1. Compile time initialization
  2. Run time initialization

1. Compile Time Initialization

It means to provide the value to the variable during the compilation of the program. If the programmer didn’t provide any value then the compiler will provide some default value to the variables in some cases. Generally, this type of initialization helpful when the programmer wants to provide some default value.

Example :

// C# program to demonstrate the 
// Compile Time Initialization
using System;
class Geeks {
      
        // only declaration, compiler will 
        // provide the default value 0 to it
        int y;
      
    // Main Method
    public static void Main(String []args)
    {
          
        // Compile Time Initialization of variable 'x'
        // Assigning value 32 to x
        int x = 32;    
          
        // printing the value
        Console.WriteLine("Value of x is "+x);
          
        // creating object to access
        // the variable y
        Geeks gfg = new Geeks(); 
          
        // printing the value
        Console.WriteLine("Value of y is "+gfg.y);
    }
}

Output :

Value of x is 32
Value of y is 0

2. Run Time Initialization

In this, the user has to enter the value and that value is copied to the required variable. In this type of initialization, there is one more possibility in which value is assigned to variable after completion of a function call.

Example:

Input : 45
Output : Value of num is 45

Input : 27
Output : Value of num is 27

// C# program to demonstrate the 
// Run Time Initialization
using System;
class Geeks {
      
    // Main Method
    public static void Main(String []args)
    {
          
        // Value will be taken from user 
        // input and assigned to variable
        // num
        int num = Convert.ToInt32(Console.ReadLine());
  
        // printing the result
        Console.WriteLine("Value of num is " + num);
  
    }
}

Output :

Value of num is 45

C# | Literals


The fixed values are called as Literal. Literal is a value that is used by the variables. Values can be either an integer, float or string, etc. 

// Here 100 is a constant/literal.
int x = 100; 

Literals can be of the following types: 

  • Integer Literals
  • Floating-point Literals
  • Character Literals
  • String Literals
  • Null Literals
  • Boolean Literals

Integer Literals: A literal of integer type is known as the integer literal. It can be octal, decimal, binary, or hexadecimal constant. No prefix is required for the decimal numbers. A suffix can also be used with the integer literals like U or are used for unsigned numbers while or are used for long numbers. By default, every literal is of int type. For Integral data types (byte, short, int, long), we can specify literals in the ways:

  • Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
  • Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146; 
  • Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9 and characters are a-f. We can use both uppercase and lowercase characters. As we know that c# is a case-sensitive programming language but here c# is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face; 
  • Binary literals (Base 2): In this form, the allowed digits are only 1’s and 0’s.
// The binary number should be prefix with 0b.
int x = 0b101

Examples: 

07778    // invalid: 8 is not an octal digit 
045uu    // invalid: suffix (u) is repeated
0b105    // invalid: 5 is not a binary digit
0b101    // valid binary literal
456      // valid decimal literal
02453    // valid octal literal 
0x65d    // valid hexadecimal literal 
12356    // valid int literal 
304U     // valid unsigned int literal 
3078L    // valid long literal 
965UL    // valid unsigned long literal 

Program:

// C# program to illustrate the use of Integer Literals
using System;
 
class Geeks{
 
    // Main method
    public static void Main(String[] args)
    {
       
        // decimal-form literal
        int a = 101;
 
        // octal-form literal
        int b = 0145;
 
        // Hexa-decimal form literal
        int c = 0xFace;
       
        // binary-form literal
        int x = 0b101;
         
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
        Console.WriteLine(x);
    }
}
101
145
64206
5

Floating-point Literals: The literal which has an integer part, a decimal point, a fractional part, and an exponent part is known as the floating-point literal. These can be represented either in decimal form or exponential form.

Examples:  

Double d = 3.14145       // Valid
Double d = 312569E-5      // Valid
Double d = 125E             // invalid: Incomplete exponent 
Double d = 784f            // valid
Double d = .e45           // invalid: missing integer or fraction

Program:

// C# program to illustrate the use of
// floating-point literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
        // decimal-form literal
        double a = 101.230;
 
        // It also acts as decimal literal
        double b = 0123.222;
 
        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}

Output: 

101.23
123.222

Note: By default, every floating-point literal is of double type and hence we can’t assign directly to float variable. But we can specify floating-point literal as float type by suffixed with f or F. We can specify explicitly floating-point literal as the double type by suffixed with d or D, of course, this convention is not required.

Character Literals: For character data types we can specify literals in 3 ways: 

  • Single quote: We can specify literal to char data type as single character within single quote.
char ch = 'a';
  • Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
  • Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';
Escape SequenceMeaning
\\\ character
\’‘ character
\?? character
\”” character
\bBackspace
\aAlert or Bell
\nNew Line
\fForm Feed
\rCarriage Return
\vVertical Tab
\xhh…Hexadecimal number of one or more digits

Example : 

// C# program to illustrate the use of char literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
 
        // character literal within single quote
        char ch = 'a';
 
        // Unicode representation
        char c = '\u0061';
 
        Console.WriteLine(ch);
        Console.WriteLine(c);
 
        // Escape character literal
        Console.WriteLine("Hello\n\nGeeks\t!");
    }
}
a
a
Hello

Geeks    !

String Literals: Literals which are enclosed in double quotes(“”) or starts with @”” are known as the String literals. 

Examples:  

String s1 = "Hello Geeks!";

String s2 = @"Hello Geeks!";

Program: 

// C#  program to illustrate the use of String literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
 
        String s = "Hello Geeks!";
        String s2 = @"Hello Geeks!";
 
        // If we assign without "" then it
        // treats as a variable
        // and causes compiler error
        // String s1 = Geeks;
 
        Console.WriteLine(s);
        Console.WriteLine(s2);
    }
}

Output: 

Hello Geeks!
Hello Geeks!

Boolean Literals: Only two values are allowed for Boolean literals i.e. true and false.

Example: 

bool b = true;
bool c = false;

Program: 

// C# program to illustrate the use
// of boolean literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
        bool b = true;
        bool c = false;
 
        // these will give compile time error
        // bool d = 0;
        // bool e = 1;
        // Console.WriteLine(d);
        // Console.WriteLine(e);
 
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
}

Output: 

True
False

C# | Operators

Operators are the foundation of any programming language. Thus the functionality of C# language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C#, operators Can be categorized based upon their different functionality :

In C#, Operators can also categorized based upon Number of Operands : 

  • Unary Operator: Operator that takes one operand to perform the operation.
  • Binary Operator: Operator that takes two operands to perform the operation.
  • Ternary Operator: Operator that takes three operands to perform the operation.
     

Arithmetic Operators

These are used to perform arithmetic/mathematical operations on operands. The Binary Operators falling in this category are :

  • Addition: The ‘+’ operator adds two operands. For example, x+y.
  • Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
  • Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
  • Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
  • Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y.

Example:

// C# program to demonstrate the working
// of Binary Arithmetic Operators
using System;
namespace Arithmetic
{
    class GFG
    {
         
        // Main Function
        static void Main(string[] args)
        {
             
            int result;
            int x = 10, y = 5;
             
            // Addition
            result = (x + y);
            Console.WriteLine("Addition Operator: " + result);
             
            // Subtraction
            result = (x - y);
            Console.WriteLine("Subtraction Operator: " + result);
             
            // Multiplication
            result = (x * y);
            Console.WriteLine("Multiplication Operator: "+ result);
             
            // Division
            result = (x / y);
            Console.WriteLine("Division Operator: " + result);
             
            // Modulo
            result = (x % y);
            Console.WriteLine("Modulo Operator: " + result);
        }
    }
}

Output:

Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0

The ones falling into the category of Unary Operators are:

  • Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x
    And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.
  • Decrement: The ‘- -‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, – -x.
    And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x- –.

Example:

// C# program to demonstrate the working
// of Unary Arithmetic Operators
using System;
namespace Arithmetic {
     
    class GFG {
         
        // Main Function
        static void Main(string[] args)
        {
             
            int a = 10, res;
  
            // post-increment example:
            // res is assigned 10 only,
            // a is not updated yet
            res = a++;
             
             //a becomes 11 now
            Console.WriteLine("a is {0} and res is {1}", a, res);
          
          
            // post-decrement example:
            // res is assigned 11 only, a is not updated yet
            res = a--;
             
            //a becomes 10 now
            Console.WriteLine("a is {0} and res is {1}", a, res); 
          
          
            // pre-increment example:
            // res is assigned 11 now since a
            // is updated here itself
            res = ++a;
             
            // a and res have same values = 11
            Console.WriteLine("a is {0} and res is {1}", a, res);
          
          
            // pre-decrement example:
            // res is assigned 10 only since
            // a is updated here itself
            res = --a;
             
            // a and res have same values = 10
            Console.WriteLine("a is {0} and res is {1}",a, res);
          
            
        }
    }
}

Output:

a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10

Relational Operators

Relational operators are used for comparison of two values. Let’s see them one by one:

  • ‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true.
  • ‘!='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
  • ‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
  • ‘<‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
  • ‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
  • ‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.

Example:

// C# program to demonstrate the working
// of Relational Operators
using System;
namespace Relational {
     
class GFG {
     
    // Main Function
    static void Main(string[] args)
    {
        bool result;
        int x = 5, y = 10;
         
        // Equal to Operator
        result = (x == y);
        Console.WriteLine("Equal to Operator: " + result);
         
        // Greater than Operator
        result = (x > y);
        Console.WriteLine("Greater than Operator: " + result);
         
        // Less than Operator
        result = (x < y);
        Console.WriteLine("Less than Operator: " + result);
         
        // Greater than Equal to Operator
        result = (x >= y);
        Console.WriteLine("Greater than or Equal to: "+ result);
         
        // Less than Equal to Operator
        result = (x <= y);
        Console.WriteLine("Lesser than or Equal to: "+ result);
         
        // Not Equal To Operator
        result = (x != y);
        Console.WriteLine("Not Equal to Operator: " + result);
    }
}
}

Output:

Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True

Logical Operators

They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:

  • Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).
  • Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
  • Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.

Example:

// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical {
     
class GFG {
     
    // Main Function
    static void Main(string[] args)
    {
            bool a = true,b = false, result;
         
            // AND operator
            result = a && b;
            Console.WriteLine("AND Operator: " + result);
             
            // OR operator
            result = a || b;
            Console.WriteLine("OR Operator: " + result);
             
            // NOT operator
            result = !a;
            Console.WriteLine("NOT Operator: " + result);
         
    }
}
}

Output:

AND Operator: False
OR Operator: True
NOT Operator: False

Bitwise Operators

In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators :

  • & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
  • | (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
  • ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
  • << (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
  • >> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.

Example:

// C# program to demonstrate the working
// of Bitwise Operators
using System;
namespace Bitwise {
     
class GFG {
     
    // Main Function
    static void Main(string[] args)
    {
         int x = 5, y = 10, result;
          
            // Bitwise AND Operator
            result = x & y;
            Console.WriteLine("Bitwise AND: " + result);
             
            // Bitwise OR Operator
            result = x | y;
            Console.WriteLine("Bitwise OR: " + result);
             
            // Bitwise XOR Operator
            result = x ^ y;
            Console.WriteLine("Bitwise XOR: " + result);
             
            // Bitwise AND Operator
            result = ~x;
            Console.WriteLine("Bitwise Complement: " + result);
             
            // Bitwise LEFT SHIFT Operator
            result = x << 2;
            Console.WriteLine("Bitwise Left Shift: " + result);
             
            // Bitwise RIGHT SHIFT Operator
            result = x >> 2;
            Console.WriteLine("Bitwise Right Shift: " + result);
         
    }
}
}

Output:

Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1

Assignment Operators

Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

  • “=”(Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
    Example:
a = 10;
b = 20;
ch = 'y';
  • “+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.
    Example:
(a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.

  • “-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left.
    Example:
(a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

  • “*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.
    Example:
(a *= b) can be written as (a = a * b)

If initially value stored in a is 5. Then (a *= 6) = 30.

  • “/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
    Example:
(a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

  • “%=”(Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
    Example:
(a %= b) can be written as (a = a % b)

If initially value stored in a is 6. Then (a %= 2) = 0.

  • “<<=”(Left Shift Assignment) : This operator is combination of ‘<<‘ and ‘=’ operators. This operator first Left shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
    Example:
(a <<= 2) can be written as (a = a << 2)

If initially value stored in a is 6. Then (a <<= 2) = 24.

  • “>>=”(Right Shift Assignment) : This operator is combination of ‘>>’ and ‘=’ operators. This operator first Right shift the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
    Example:
(a >>= 2) can be written as (a = a >> 2)

If initially value stored in a is 6. Then (a >>= 2) = 1.

  • “&=”(Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This operator first “Bitwise AND” the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.
    Example:
(a &= 2) can be written as (a = a & 2)

If initially value stored in a is 6. Then (a &= 2) = 2.

  • “^=”(Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
    Example:
(a ^= 2) can be written as (a = a ^ 2)

If initially value stored in a is 6. Then (a ^= 2) = 4.

  • “|=”(Bitwise Inclusive OR) : This operator is combination of ‘|’ and ‘=’ operators. This operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
    Example :
(a |= 2) can be written as (a = a | 2)

If initially, value stored in a is 6. Then (a |= 2) = 6.

Example:

// C# program to demonstrate the working
// of Assignment Operators
using System;
namespace Assignment {
     
class GFG {
     
    // Main Function
    static void Main(string[] args)
    {
         
            // initialize variable x
            // using Simple Assignment
            // Operator "="
            int x = 15;
             
            // it means x = x + 10
            x += 10;
            Console.WriteLine("Add Assignment Operator: " + x);
             
             // initialize variable x again
            x = 20;
             
            // it means x = x - 5
            x -= 5;
            Console.WriteLine("Subtract Assignment Operator: " + x);
             
            // initialize variable x again
            x = 15;
             
            // it means x = x * 5
            x *= 5;
            Console.WriteLine("Multiply Assignment Operator: " + x);
             
            // initialize variable x again
            x = 25;
             
            // it means x = x / 5
            x /= 5;
            Console.WriteLine("Division Assignment Operator: " + x);
             
            // initialize variable x again
            x = 25;
             
            // it means x = x % 5
            x %= 5;
            Console.WriteLine("Modulo Assignment Operator: " + x);
             
            // initialize variable x again
            x = 8;
             
            // it means x = x << 2
            x <<= 2;
            Console.WriteLine("Left Shift Assignment Operator: " + x);
             
            // initialize variable x again
            x = 8;
             
            // it means x = x >> 2
            x >>= 2;
            Console.WriteLine("Right Shift Assignment Operator: " + x);
             
            // initialize variable x again
            x = 12;
             
            // it means x = x >> 4
            x &= 4;
            Console.WriteLine("Bitwise AND Assignment Operator: " + x);
             
            // initialize variable x again
            x = 12;
             
            // it means x = x >> 4
            x ^= 4;
            Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x);
             
             // initialize variable x again
            x = 12;
             
            // it means x = x >> 4
            x |= 4;
            Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x);
         
    }
}
}

Output :

Add Assignment Operator: 25
Subtract Assignment Operator: 15
Multiply Assignment Operator: 75
Division Assignment Operator: 5
Modulo Assignment Operator: 0
Left Shift Assignment Operator: 32
Right Shift Assignment Operator: 2
Bitwise AND Assignment Operator: 4
Bitwise Exclusive OR Assignment Operator: 8
Bitwise Inclusive OR Assignment Operator: 12

Conditional Operator

It is ternary operator which is a shorthand version of if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression. 

Syntax:

condition ? first_expression : second_expression;

Explanation:
condition: It must be evaluated to true or false.
If the condition is true
first_expression is evaluated and becomes the result. 
If the condition is false, 
second_expression is evaluated and becomes the result. 

Example:

// C# program to demonstrate the working
// of Conditional Operator
using System;
namespace Conditional {
     
class GFG {
     
    // Main Function
    static void Main(string[] args)
    {
            int x = 5, y = 10, result;
             
            // To find which value is greater
            // Using Conditional Operator
            result = x > y ? x : y;
             
            // To display the result
            Console.WriteLine("Result: " + result);
             
            // To find which value is greater
            // Using Conditional Operator
            result = x < y ? x : y;
             
            // To display the result
            Console.WriteLine("Result: " + result);
    }
}
}

Output :

Result: 10
Result: 5

C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)

Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. 
A programming language uses control statements to control the flow of execution of program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
The conditional statements of C#: 
 

IF Statement 
The if statement checks the given condition. If the condition evaluates to be true then the block of code/statements will execute otherwise not. 
Syntax: 
 

if(condition)
     {  
         //code to be executed  
     }  

Note: If the curly brackets { } are not used with if statements then the statement just next to it is only considered associated with the if statement. 
Example: 
 

if (condition)
   statement 1;
statement 2;

In this example, only statement 1 is considered to be associated with the if statement.
Flowchart: 
 

Example: 
 

Csharp

// C# program to illustrate if statement
using System;
 
public class GFG {
 
    public static void Main(string[] args)
    {
        string name = "Geek";
        if (name == "Geek") {
            Console.WriteLine("GeeksForGeeks");
        }
    }
}

Output: 
 

GeeksForGeeks

IF – else Statement 
The if statement evaluates the code if the condition is true but what if the condition is not true, here comes the else statement. It tells the code what to do when the if condition is false.
Syntax: 
 

    if(condition)
    {  
      // code if condition is true  
    }
    else
    {  
      // code if condition is false  
    }  
   

Flowchart: 
 

Example: 
 

Csharp

// C# program to illustrate
// if-else statement
using System;
 
public class GFG {
 
    public static void Main(string[] args)
    {
        string name = "Geek";
        if (name == "Geeks") {
            Console.WriteLine("GeeksForGeeksr");
        }
        else {
            Console.WriteLine("Geeks");
        }
    }
}

Output: 
 

Geeks

If – else – if ladder Statement 
The if-else-if ladder statement executes one condition from multiple statements. The execution starts from top and checked for each if condition. The statement of if block will be executed which evaluates to be true. If none of the if condition evaluates to be true then the last else block is evaluated. 
Syntax: 
 

        if(condition1)
        {  
            // code to be executed if condition1 is true  
        }
        else if(condition2)
        {  
            // code to be executed if condition2 is true  
        }  
        else if(condition3)
        {  
            // code to be executed if condition3 is true  
        }  
        ... 
        else
        {
            // code to be executed if all the conditions are false  
        }  
   

Flowchart: 
 

Example: 
 

Csharp

// C# program to illustrate
// if-else-if ladder
using System;
 
class GFG {
 
    public static void Main(String[] args)
    {
        int i = 20;
 
        if (i == 10)
            Console.WriteLine("i is 10");
        else if (i == 15)
            Console.WriteLine("i is 15");
        else if (i == 20)
            Console.WriteLine("i is 20");
        else
            Console.WriteLine("i is not present");
    }
}

Output: 
 

i is 20

Nested – If Statement 
if statement inside an if statement is known as nested if. if statement in this case is the target of another if or else statement. When more than one condition needs to be true and one of the condition is the sub-condition of parent condition, nested if can be used.
Syntax: 
 

        if (condition1) 
        {
             // code to be executed 
             // if condition2 is true 
             if (condition2) 
             {
                 // code to be executed 
                 // if condition2 is true 
             }
        }

Flowchart: 
 

Example:
 

csharp

// C# program to illustrate
// nested-if statement
using System;
 
class GFG {
 
    public static void Main(String[] args)
    {
        int i = 10;
 
        if (i == 10) {
 
            // Nested - if statement
            // Will only be executed if statement
            // above it is true
            if (i < 12)
                Console.WriteLine("i is smaller than 12 too");
            else
                Console.WriteLine("i is greater than 15");
        }
    }
}

Output: 
 

i is smaller than 12 too

Switch Statement 
Switch statement is an alternative to long if-else-if ladders. The expression is checked for different cases and the one match is executed. break statement is used to move out of the switch. If the break is not used, the control will flow to all cases below it until break is found or switch comes to an end. There is default case (optional) at the end of switch, if none of the case matches then default case is executed.
Syntax: 
 

switch (expression)
 {
case value1: // statement sequence
             break;
case value2: // statement sequence
             break;
.
.
.
case valueN: // statement sequence
             break;
default: // default statement sequence
}

Flow Diagram of Switch – case : 
 

Flow Diagram of Switch-Case statement

Example: 
 

Csharp

// C# example for switch case
using System;
 
public class GFG
{
    public static void Main(String[] args)
    {
        int number = 30;
        switch(number)
        {
        case 10: Console.WriteLine("case 10");
                 break;
        case 20: Console.WriteLine("case 20");
                 break;
        case 30: Console.WriteLine("case 30");
                 break;
        default: Console.WriteLine("None matches");
                 break;
        }
    }
}

Output: 
 

case 30

Nested switch 
Nested Switch case are allowed in C# . In this case, switch is present inside other switch case. Inner switch is present in one of the cases in parent switch.
Example: 
 

Csharp

// C# example for nested switch case
using System;
 
public class GFG
{
    public static void Main(String[] args)
    {
        int j = 5;
 
        switch (j)
        {
            case 5: Console.WriteLine(5);
                    switch (j - 1)
                   {
                    case 4: Console.WriteLine(4);
                            switch (j - 2)
                          {
                            case 3: Console.WriteLine(3);
                                    break;
                         }
                    break;
                }
                break;
            case 10: Console.WriteLine(10);
                     break;
            case 15: Console.WriteLine(15);
                     break;
            default: Console.WriteLine(100);
                     break;
        }
 
    }
}

Output: 
 

5
4
3

Switch Statement in C#

In C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type. The expression is checked for different cases and the one match is executed.

Syntax:

switch (expression) {

case value1: // statement sequence
     break;

case value2: // statement sequence
     break;
.
.
.
case valueN: // statement sequence
     break;

default:    // default statement sequence
}

Flow Chart:

switch statement in C#

Important points to remember:

  • In C#, duplicate case values are not allowed.
  • The data type of the variable in the switch and value of a case must be of the same type.
  • The value of a case must be a constant or a literal. Variables are not allowed.
  • The break in switch statement is used to terminate the current sequence.
  • The default statement is optional and it can be used anywhere inside the switch statement.
  • Multiple default statements are not allowed.

Example:

// C# program to illustrate
// switch case statement
using System;
  
public class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        int nitem = 5;
        switch (nitem) {
  
        case 1:
            Console.WriteLine("case 1");
            break;
  
        case 5:
            Console.WriteLine("case 5");
            break;
  
        case 9:
            Console.WriteLine("case 9");
            break;
  
        default:
            Console.WriteLine("No match found");
            break;
        }
    }
}
Output:
case 5

Why do we use Switch Statements instead of if-else statements?

We use a switch statement instead of if-else statements because if-else statement only works for a small number of logical evaluations of a value. If you use if-else statement for a larger number of possible conditions then, it takes more time to write and also become difficult to read.

Example: Using if-else-if statement

// C# program to illustrate
// if-else statement
using System;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // taking two strings value
        string topic;
        string category;
  
        // taking topic name
        topic = "Inheritance";
  
                // using compare function of string class
        if ((String.Compare(topic, "Introduction to C#") == 0) || 
            (String.Compare(topic, "Variables") == 0) || 
            (String.Compare(topic, "Data Types") == 0))
        {
            category = "Basic";
        }
          
                // using compare function of string class
        else if ((String.Compare(topic, "Loops") == 0) || 
                 (String.Compare(topic, "If Statements") == 0) || 
                 (String.Compare(topic, "Jump Statements") == 0)) 
        {
            category = "Control Flow";
        }
              
                // using compare function of string class
        else if ((String.Compare(topic, "Class & Object") == 0) || 
                 (String.Compare(topic, "Inheritance") == 0) || 
                 (String.Compare(topic, "Constructors") == 0)) 
        {
            category = "OOPS Concept";
        }
          
        else 
        {
            category = "Not Mentioned";
        }
  
        System.Console.Write("Category is " + category);
    }
}
Output:
Category is OOPS Concept

Explanation: As shown in the above program the code is not excessive but, it looks complicated to read and took more time to write. So we use a switch statement to save time and write optimized code. Using switch statement will provide a better readability of code.

Example: Using Switch Statement

// C# program to illustrate
// switch statement
using System;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // taking two strings value
        string topic;
        string category;
  
        // taking topic name
        topic = "Inheritance";
          
        // using switch Statement
        switch(topic)
        {
            case "Introduction to C#":
            case "Variables":
            case  "Data Types":
                   
                category = "Basic";
                break;
                  
             case "Loops":
             case"If Statements":
             case"Jump Statements":
                   
                category = "Control Flow";
                break;
                  
             case "Class & Object":
             case "Inheritance":
             case "Constructors":
                   
                category = "OOPS Concept";
                break;
                  
             // default case 
             default:
                category = "Not Mentioned";
                break;
                  
        }
          
        System.Console.Write("Category is " + category);
    }
}
Output:
Category is OOPS Concept

Using goto in the Switch Statement

You can also use goto statement in place of the break in the switch statement. Generally, we use a break statement to exit from the switch statement. But in some situations, the default statement is required to be executed, so we use the goto statement. It allows executing default condition in the switch statement. The goto statement is also used to jump to a labeled location in C# program.

Example:

// C# program to illustrate the
// use of goto in switch statement
using System;
  
public class GFG {
  
// Main Method
public static void Main(String[] args)
    {
        int greeting = 2;
  
        switch (greeting) {
        case 1:
            Console.WriteLine("Hello");
            goto default;
        case 2:
            Console.WriteLine("Bonjour");
            goto case 3;
        case 3:
            Console.WriteLine("Namaste");
            goto default;
        default:
            Console.WriteLine("Entered value is: " + greeting);
            break;
        }
    }
}
Output:
Bonjour
Namaste
Entered value is: 2

Loops in C#

Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops. Loops are mainly divided into two categories: Entry Controlled Loops: The loops in which condition to be tested is present in beginning of loop body are known as Entry Controlled Loopswhile loop and for loop are entry controlled loops. 1. while loop The test condition is given in the beginning of the loop and all statements are executed till the given Boolean condition satisfies when the condition becomes false, the control will be out from the while loop. Syntax:

while (boolean condition)
{
   loop statements...
}

Flowchart: while loop Example: 

csharp

// C# program to illustrate while loop
using System;
 
class whileLoopDemo
{
    public static void Main()
    {
        int x = 1;
  
        // Exit when x becomes greater than 4
        while (x <= 4)
        {
            Console.WriteLine("GeeksforGeeks");
  
            // Increment the value of x for
            // next iteration
            x++;
        }
    }
}

Output:

GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Time Complexity: O(1)
Auxiliary Space: O(1)

2. for loop for loop has similar functionality as while loop but with different syntax. for loops are preferred when the number of times loop statements are to be executed is known beforehand. The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is done in one line in for loop thereby providing a shorter, easy to debug structure of looping.

for (loop variable initialization ; testing condition; 
                              increment / decrement)
{    
    // statements to be executed
}

Flowchart: for-loop-in-java 1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is the starting point of for loop. An already declared variable can be used or a variable can be declared, local to loop only. 2. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit condition for a loop. It must return a boolean value true or false. When the condition became false the control will be out from the loop and for loop ends. 3. Increment / Decrement: The loop variable is incremented/decremented according to the requirement and the control then shifts to the testing condition again. Note: Initialization part is evaluated only once when the for loop starts. Example: 

csharp

// C# program to illustrate for loop.
using System;
 
class forLoopDemo
{
    public static void Main()
    {
        // for loop begins when x=1
        // and runs till x <=4
        for (int x = 1; x <= 4; x++)
            Console.WriteLine("GeeksforGeeks");
    }
}

Output:

GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Time Complexity: O(1)
Auxiliary Space: O(1)

Exit Controlled Loops: The loops in which the testing condition is present at the end of loop body are termed as Exit Controlled Loopsdo-while is an exit controlled loop. Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing condition is present at the end of loop body. 1. do-while loop do while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure because it checks the condition after executing the statements. Syntax :

do
{
    statements..
}while (condition);

Flowchart: do-while Example: 

csharp

// C# program to illustrate do-while loop
using System;
 
class dowhileloopDemo
{
    public static void Main()
    {
        int x = 21;
        do
        {
            // The line will be printed even
            // if the condition is false
            Console.WriteLine("GeeksforGeeks");
            x++;
        }
        while (x < 20);
    }
}

Output:

GeeksforGeeks

Infinite Loops: The loops in which the test condition does not evaluate false ever tend to execute statements forever until an external force is used to end it and thus they are known as infinite loops. Example: 

csharp

// C# program to demonstrate infinite loop
using System;
 
class infiniteLoop
{
    public static void Main()
    {
        // The statement will be printed
        // infinite times
        for(;;)
        Console.WriteLine("This is printed infinite times");
    }
}

Output:

This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
..........

Nested Loops: When loops are present inside the other loops, it is known as nested loops. Example: 

csharp

// C# program to demonstrate nested loops
using System;
 
class nestedLoops
{
    public static void Main()
    {
        // loop within loop printing GeeksforGeeks
       for(int i = 2; i < 3; i++)
             for(int j = 1; j < i; j++)
                 Console.WriteLine("GeeksforGeeks");
    }
}

Output:

GeeksforGeeks

continue statement: continue statement is used to skip over the execution part of loop on a certain condition and move the flow to next updation part. Flowchart:  Example: 

csharp

// C# program to demonstrate continue statement
using System;
 
class demoContinue
{
    public static void Main()
    {   
        // GeeksforGeeks is printed only 2 times
        // because of continue statement
        for(int i = 1; i < 3; i++)
        {
            if(i == 2)
              continue;
             
            Console.WriteLine("GeeksforGeeks");
        }
    }

Output:

GeeksforGeeks

C# | Jump Statements (Break, Continue, Goto, Return and Throw)

In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. There are five keywords in the Jump Statements:

  • break
  • continue
  • goto
  • return
  • throw
     

break statement

The break statement is used to terminate the loop or statement in which it present. After that, the control will pass to the statements that present after the break statement, if available. If the break statement present in the nested loop, then it terminates only those loops which contains break statement. 
Flowchart:
 

Example:
 

// C# program to illustrate the
// use of break statement
using System;
 
class Geeks {
 
    // Main Method
    static public void Main()
    {
 
        // GeeksforGeeks is printed only 2 times
        // because of break statement
        for (int i = 1; i < 4; i++)
        {
            if (i == 3)
                break;
 
            Console.WriteLine("GeeksforGeeks");
        }
    }
}
Output: 
GeeksforGeeks
GeeksforGeeks

 

continue statement

This statement is used to skip over the execution part of the loop on a certain condition. After that, it transfers the control to the beginning of the loop. Basically, it skips its following statements and continues with the next iteration of the loop.
 

Example:
 

// C# program to illustrate the
// use of continue statement
using System;
 
class Geeks {
 
    // Main Method
    public static void Main()
    {
         
        // This will skip 4 to print
        for (int i = 1; i <= 10; i++) {
 
            // if the value of i becomes 4 then
            // it will skip 4 and send the
            // transfer to the for loop and
            // continue with 5
            if (i == 4)
                continue;
 
            Console.WriteLine(i);
        }
    }
}
Output: 
1
2
3
5
6
7
8
9
10

 

goto statement

This statement is used to transfer control to the labeled statement in the program. The label is the valid identifier and placed just before the statement from where the control is transferred.
 

Example:
 

// C# program to illustrate the
// use of goto statement
using System;
 
class Geeks {
 
    // Main Method
    static public void Main()
    {
        int number = 20;
        switch (number) {
 
        case 5:
            Console.WriteLine("case 5");
            break;
        case 10:
            Console.WriteLine("case 10");
            break;
        case 20:
            Console.WriteLine("case 20");
 
            // goto statement transfer
            // the control to case 5
            goto case 5;
 
        default:
            Console.WriteLine("No match found");
             
        }
    }
}
Output: 
case 20
case 5

 

return statement

This statement terminates the execution of the method and returns the control to the calling method. It returns an optional value. If the type of method is void, then the return statement can be excluded.
Example:
 

// C# program to illustrate the
// use of return statement
using System;
 
class Geeks {
 
    // creating simple addition function
    static int Addition(int a)
    {
 
        // add two value and
        // return the result of addition
        int add = a + a;
        
        // using return statement
        return add;
    }
 
    // Main Method
    static public void Main()
    {
        int number = 2;
 
        // calling addition function
        int result = Addition(number);
        Console.WriteLine("The addition is {0}", result);
    }
}
Output: 
The addition is 4

 

throw statement

This is used to create an object of any valid exception class with the help of new keyword manually. The valid exception must be derived from the Exception class.
Example:
 

// C# Program to illustrate the use
// of throw keyword
using System;
 
class Geeks {
     
     // taking null in the string
     static string sub = null;
         
    // method to display subject name   
    static void displaysubject(string sub1)
    {
        if (sub1  == null)
            throw new NullReferenceException("Exception Message");
             
    }
 
// Main Method   
static void Main(string[] args)
{
     
    // using try catch block to
    // handle the Exception
    try
    {
         
        // calling the static method
        displaysubject(sub);
    }
     
    catch(Exception exp)
    {
        Console.WriteLine(exp.Message );
    }                    
}
 
}
Output: 
Exception Message
Here are the key details about C#:
Object-Oriented Programming (OOP):
C# is designed around the principles of object-oriented programming, which allows developers to model real-world entities and their interactions using classes and objects.

Syntax and Structure:
C# syntax is similar to that of other C-like languages, making it relatively easy to learn if you're familiar with languages like C++ or Java.
It uses curly braces {} to define code blocks and semicolons ; to separate statements.

.NET Framework and .NET Core/.NET 5+:

Originally developed for the .NET Framework, C# applications can run on Windows and interact with various Microsoft technologies.
With the introduction of .NET Core and later .NET 5+, C# has become more cross-platform, enabling development on Windows, macOS, and Linux.

Visual Studio IDE:
Microsoft's Visual Studio is the primary integrated development environment (IDE) for C# development, providing tools for coding, debugging, and designing user interfaces.

Language Features:
C# includes modern language features like generics, delegates, lambdas, events, properties, and more, which enhance code clarity and expressiveness.

Asynchronous Programming:
C# has built-in support for asynchronous programming through the async and await keywords, making it easier to write responsive applications.

Windows Applications:
C# is commonly used for building Windows applications, including desktop applications and Universal Windows Platform (UWP) apps.

Web Applications:
ASP.NET, a web framework developed by Microsoft, allows developers to build dynamic web applications using C# on the server side.

Game Development:
C# is widely used in game development, especially in conjunction with the Unity game engine.

Language Interoperability:

C# is designed to work well with other .NET languages like Visual Basic .NET (VB.NET) and F#.
It can also interface with existing native code using platform invoke (P/Invoke) or COM interoperability.

Memory Management:
C# uses automatic memory management through a process called garbage collection, which helps developers avoid manual memory management pitfalls.

Security and Type Safety:
C# emphasizes type safety and provides features like managed code execution, which contributes to the security of applications.

Standard Libraries:

C# has a rich standard library that provides classes and functions for common tasks, such as file I/O, networking, data serialization, and more.

Continuous Evolution:
C# is continuously evolving, with new features and improvements introduced in each new version.

Post a Comment

0 Comments