VISUAL PROGRAMMING
BY
    THATIKONDA RADHIKA REDDY
Syllabus:
Topics to be Covered:
• Introduction to .NET Framework and    • Operators
  Visual Studio.NET
                                        • Casting
• Introduction to .NET Framework –
  The .Net Framework,                   • Control Structures
• C# language.                          • Conditionals
• Visual Studio.NET- using the Visual   • Loops
  Studio IDE.                           • Namespaces
• C# Language and Syntax – Data Types
                                        • Preprocessor Directives
• Variables
                                        • Keywords
• Constants
                                        • Strings and Regular Expressions
Visual Programming
• Any language that uses the graphics or blocks that are
  already defined with the code and we just need to use those
  blocks without worrying about the lines of code is known as
  a visual programming language.
• Applications of Visual Programming language:
• Multimedia
• Educational Purpose
• Video Games
Introduction to .NET Framework
• .NET is a software framework that is designed and
 developed by Microsoft.
• The first version of the .Net framework was 1.0 which
  came in the year 2002.
• The .NET Framework provides a runtime environment
  and a set of libraries and tools for building and running
  applications on Windows operating systems.
• The framework includes a variety of programming languages, such as
  C#, F#, and Visual Basic, and supports a range of application types,
  including desktop, web, mobile, and gaming applications.
• There is a variety of programming languages available on the .Net
  platform, VB.Net and C# being the most common ones.
• It provides many functionalities and also supports industry standards.
• .NET Framework supports more than 60 programming languages of
  which 11 programming languages are designed and developed by
  Microsoft.
• The remaining Non-Microsoft Languages are supported by .NET
  Framework but not designed and developed by Microsoft.
11 Programming Languages which are designed and developed by
Microsoft are:
• C#.NET
• VB.NET
• C++.NET
• J#.NET
• F#.NET
• JSCRIPT.NET
• WINDOWS POWERSHELL
• IRON RUBY
• IRON PYTHON
• C OMEGA
• ASML(Abstract State Machine Language)
Basic Architecture and
Component Stack of .NET Framework
• The .NET Framework is composed of four main components:
• Common Language Runtime (CLR)
• Framework Class Library (FCL),
• Core Languages (WinForms, ASP.NET, and ADO.NET), and
• Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity
  Framework, Parallel LINQ, Task Parallel Library, etc.)
CLR (Common Language Runtime)
• It is a program execution engine that loads and executes the program.
  It converts the program into native code.
• It acts as an interface between the framework and operating system.
• The .NET application Source Code gets compiled into Microsoft
  Intermediate language (MSIL) which is also called Intermediate
  language (IL) or Common Intermediate language (CIL) code.
• NET applications run on top of a virtual environment called Common
  Language Runtime (CLR).
• CLR contains a component called Just-In-Time Compiler (JIT) which
  will convert the Intermediate language into native code which can be
  understood by the underlying operating system.
Common Language Specification (CLS):
• It is responsible for converting the different .NET programming language
  syntactical rules and regulations into CLR understandable format.
• Basically, it provides Language Interoperability.
• Language Interoperability means providing execution support to other
  programming languages also in .NET framework.
• Language Interoperability can be achieved in two ways :
• Managed Code
• Unmanaged Code
CTS (Common Type System)
• Every programming language has its own data type system, so CTS is
  responsible for understanding all the data type systems of .NET
  programming languages and converting them into CLR understandable
  format which will be a common format.
• There are 2 Types of CTS
• Value Types: Value Types will store the value directly into the memory
  location. These types work with stack mechanisms only.
• Reference Types: Reference Types will contain a memory address of value
  because the reference types won’t store the variable value directly in
  memory. These types work with Heap mechanism. CLR allot memory for
  these at Runtime
• Garbage Collector:
• It is used to provide the Automatic Memory Management feature. If
  there was no garbage collector, programmers would have to write the
  memory management codes which will be a kind of overhead on
  programmers.
• JIT(Just In Time Compiler):
• It is responsible for converting the CIL(Common Intermediate
  Language) into machine code or native code using the Common
  Language Runtime environment.
CLR (Common Language Runtime)
The CLR is the heart of the .NET Framework, responsible for
managing the execution of .NET applications. It provides
several essential services:
• Memory Management (Garbage Collection):
  The CLR automatically manages memory by reclaiming
  unused memory through garbage collection. This ensures
  efficient memory utilization and minimizes memory leaks.
• Code Verification:
  Before execution, the CLR verifies the integrity and safety of
  managed code to prevent security vulnerabilities and crashes.
• Just-In-Time (JIT) Compilation:
  The CLR compiles Intermediate Language (IL) code into native
  machine code on-demand, optimizing performance by converting code
  to a format that the computer's processor can execute.
• Security:
  The CLR enforces various security measures to prevent unauthorized
  access and code execution. Code access security and role-based
  security are implemented to ensure safe execution.
• Exception Handling:
  The CLR facilitates structured and consistent exception handling,
  promoting robust error management and graceful application recovery.
 FCL (Framework Class Library)
• A large number of class libraries are present in this framework which
  is known as FCL.
• It is a standard library that is a collection of thousands of classes and
  used to build an application.
• The BCL (Base Class Library) is the core of the FCL and provides
  basic functionalities.
Types of Applications:
• Mainly the applications that are built in the .Net framework are divided into the
  following three categories :
• WinForms:
• Form-Based applications are considered under this category. In simple terms.
• we can say client-based applications that read and write the file system come
  under this category.
• ASP .NET:
• Web-based applications come under this category.
• ASP.Net is a framework for the web and it provides an awesome integration of
  HTML, CSS, and JavaScript which makes it useful to develop web applications,
  websites, and web services.
• Web services were added in .Net Framework 2.0 and considered as a part of
  ASP.NET web applications.
• ADO .NET: It includes the applications that are developed to
  communicate with the database like MS SQL Server, Oracle, etc. It
  mainly consists of classes that can be used to connect, retrieve, insert,
  and delete data.
 WPF (Windows Presentation Foundation):
• Windows Presentation Foundation (WPF) is a graphical
  subsystem given by Microsoft that uses DirectX and is used in
  Windows-based applications for rendering UI (User Interface).
• WPF was initially released as part of .NET Framework 3.0 in
  2006 and was previously known as “Avalon”.
WCF (Windows Communication Foundation):
• It is a framework for building connected and service-oriented
  applications used to transmit data asynchronously from one
  service endpoint to another service point.
• It was previously known as the Indigo.
• WF (Windows Workflow Foundation):
• It is a technology given by Microsoft that provides a platform
  for building workflows within .Net applications.
• Card Space:
• It is a Microsoft .NET Framework software client that is
  designed to let users provide their digital identity to online
  services in a secure, simple, and trusted way.
• LINQ (Language Integrated Query)
• It is introduced in .Net framework version 3.5. Basically, it is
  a query language used to make the query for data sources
  with VB or C# programming languages.
Entity Framework
• It is an open–source ORM (Object Relational Mapping) based
  framework that comes into .Net Framework version 3.5.
• It enables the .Net developer to work with a database using .Net objects.
• Before the entity framework, .Net developers performed a lot of things
  related to databases. Like to open a connection to the database,
  developers have to create a Data Set to fetch or submit the data to the
  database, convert data from the Data Set to .NET objects, or vice-versa.
• It creates difficulties for developers and also it was an error-prone
  process, then “Entity Framework” comes to automate all these database-
  related activities for the application.
• So, Entity Framework allows the developers to work at a higher level of
  abstraction.
• Parallel LINQ (Language Integrated Query):
• It comes in .Net Framework version 4.0 and is also termed PLINQ. It
  provides a concurrent query execution engine for LINQ. It executes
  the LINQ in parallel such that it tries to use as much processing power
  the system on which it is executing.
• TPL (Task Parallel Library):
• It is a set of public types and APIs. It allows the developers to be more
  productive by simplifying the process of adding concurrency and
  parallelism to .Net applications.
• NET API For Store/UWP Apps:
• In 2012, Microsoft added some APIs for creating UWP(Universal
  Windows Platform) apps for Windows using C# or VB.
• Task-Based Asynchronous Model:
• It is a model used to describe the asynchronous operations and tasks in
  the .Net Framework.
Features of .NET Framework
C# Introduction:
• C# is a simple, modern, general-purpose, object-oriented
  programming language developed by Microsoft within
  its .NET initiative led by Anders Hejlsberg.
• C# (pronounced "C sharp") is widely used for developing
  different applications, including desktop, web, mobile, cloud,
  and gaming applications.
• C# enables developers to build secure and robust.NET
  applications.
Key features of C#:
• Object-Oriented:
• C# language is an object-oriented programming language,
  which means it's based on the concept of classes and objects.
• It supports encapsulation, inheritance, and polymorphism,
  allowing developers to build modular and extensible code.
• Type Safety:
• C# is statically typed, which means that variable types are
  defined at compile-time.
• This leads to enhanced type safety and can catch type-related
  errors early in the development process.
• Garbage Collection:
• C# uses automatic memory management through a process
  called garbage collection.
• This helps developers avoid memory leaks and reduces the
  complexity of memory management.
• Language Features:
• C# includes a range of modern programming language features
  such as properties, events, delegates, lambda expressions, and
  LINQ (Language Integrated Query) for querying data.
• Cross-Platform Development:
• Due to the emergence of .NET Core, followed by .NET 5 and
  subsequent versions, C# has evolved into a cross-platform
  programming language.
• This evolution enables developers to create C# applications that
  are compatible with diverse operating systems, encompassing not
  only Windows but also macOS and a variety of Linux
  distributions.
• Extensive Standard Library:
• C# benefits from the extensive .NET Standard Library, which
  provides a rich set of classes and APIs for various programming
  tasks, including file I/O, networking, data manipulation, and more.
• Integration with Microsoft Technologies:
• C# is tightly integrated with various Microsoft technologies, such
  as the Windows operating system, Microsoft Azure cloud
  services, and various development tools like Visual Studio.
• Support for Modern Software Development:
• C# supports various programming paradigms, including
  imperative, declarative, and functional programming.
• It also provides features to support asynchronous programming,
  making it suitable for building responsive and scalable
  applications.
Applications of c#
• Web Applications: C# can be used to build server-side components
  for web applications. ASP.NET, a popular web framework, allows
  developers      to    create     dynamic      and    interactive   web
  applications. ASP.NET Core further extends C#'s capabilities for
  building cross-platform web applications.
• Game Development (Unity): C# is the primary scripting language for
  the Unity game engine. Game developers use C# to implement game
  logic, interactions, and user interfaces in various genres of games.
• Mobile App Development (Xamarin): With Xamarin, C# is used to
  develop cross-platform mobile apps for iOS and Android platforms.
  Code can be shared across both platforms, streamlining
  development.
• Cloud Services (Azure): C# is employed to create cloud-based
  applications and services using Microsoft Azure. It's used for tasks
  like data storage, serverless computing, and artificial intelligence
  integration.
• Financial Software: C# is employed in creating financial applications,
  including trading platforms, algorithmic trading systems, and tools for
  financial analysis.
• Educational Software: C# is used to develop interactive educational
  applications, e-learning platforms, and educational games.
• IoT Applications (Windows IoT Core): C# language finds utility in
  constructing applications for the Internet of Things (IoT), facilitating
  the connection of devices and sensors to cloud services.
Program Structure:
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
// my first program in C# //
/*multi line comments*/
Console.WriteLine("Hello World");
}
}
}
C# Data Types
• C# is a strongly typed language, which means that variables must be
  explicitly declared with their data types.
• When declaring a variable in C#, we need to specify the variable's data
  type, indicating the kind of values it can store.
• Variables in C# are broadly classified into two types:
• Value types and
• Reference types.
Value 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.
• 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.
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.
• 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.
• Character Types :
• The character types represents a UTF-16 code unit or represents the
  16-bit Unicode character.
• 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.
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.
• String : It represents a sequence of Unicode characters and its type
  name is System.String. So, string and String are equivalent.
• string s1 = "hello"; // creating through string keyword
• String s2 = "welcome"; // creating through String class
C# Variables
• Variables are fundamental building blocks in C# programming,
  serving as containers for holding and manipulating data.
• They enable us to work with different types of information, from
  numbers to text and more.
• Variables are declared by specifying their type and name.
• Variables have a scope, which defines where they can be accessed
  within your code.
Rules for Naming Variables in C#
• Examples of valid       • Examples of invalid
  variable names in C#:     variable names:
• age                     • 123variable (starts with a digit)
• firstName               • my-variable (contains hyphens)
• _privateVariable        • class (reserved keyword)
• totalAmount             • for (reserved keyword)
• studentList             • FirstName and firstname (case
• isReady                   mismatch)
• itemCount
Types of Variables
• Local variables
• Instance variables or Non – Static Variables
• Static Variables or Class Variables
• Constant Variables
• Readonly Variables
Local variables
• A variable defined within a block or method or constructor is called
  local variable.
• These variables are created when the block is entered or the function is
  called and destroyed after exiting from the block or when the call
  returns from the function.
• The scope of these variables exists only within the block in which the
  variable is declared. i.e. we can access these variables only within that
  block.
Instance Variables or Non – Static Variables
• Instance variables are non-static variables and are declared in a class
  but outside any method, constructor or block.
• As instance variables are declared in a class, these variables are
  created when an object of the class is created and destroyed when the
  object is destroyed.
Static Variables or Class Variables
• Static variables are also known as Class variables. If a variable is
  explicitly declared with the static modifier or if a variable is declared
  under any static block then these variables are known as static
  variables.
• Static variables are created at the start of program execution and
  destroyed automatically when execution ends.
• Note: To access static variables, there is no need to create any object
  of that class, simply access the variable as:
• class_name.variable_name;
Constants Variables
• If a variable is declared by using the keyword “const” .
• It as a constant variable and these constant variables can’t be modified
  once after their declaration.
• So it’s must initialize at the time of declaration only.
• Otherwise it will provides an error.
Read-Only Variables
• If a variable is declared by using the readonly keyword then it will be
  read-only variables and these variables can’t be modified like
  constants but after initialization.
• It’s not compulsory to initialize a read-only variable at the time of the
  declaration, they can also be initialized under the constructor.
• If we not provide any value to the read only variable then it print the
  default value of Data type as 0.
C# Keywords:
• C# keywords are predefined words that have specific meanings and
  functionalities within the language.
• They serve as fundamental building blocks for writing code and
  defining the syntax and behaviour of programs.
• These C# keywords cannot be used as variable, class, or interface
  identifier names.
Keywords         Keywords                 Keywords           Keywords
 abstract            as                     base                bool
  break             byte                    case                catch
   char           checked                   class               const
 continue         decimal                  default            delegate
   do             double                     else              enum
  event           explicit                 extern               false
  finally           fixed                   float                for
 foreach            goto                      if               implicit
    in      in (generic modifier)            int              interface
 internal            is                     lock                long
namespace           new                      null              object
 operator           out             out (generic modifier)    override
 params           private                 protected            public
 readonly            ref                   return               sbyte
  sealed           short                    sizeof           stackalloc
  static           string                   struct             switch
   this            throw                    true                 try
  typeof            uint                    ulong            unchecked
 unsafe            ushort                   using            using static
   void           volatile                  while
C# Operators
Operators are symbols that are used to perform operations on operands.
Types of Operators:
1. Basic Assignment Operator
2. Arithmetic Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Ternary Operator
7. Bitwise and Bit Shift Operators
8. Compound Assignment Operators
Basic Assignment Operator
• Basic assignment operator (=) is used to assign values to variables.
using System;
class AssignmentOperator
 {
public static void Main(string[] args)
 {
int firstNumber, secondNumber;
firstNumber = 10;
Console.WriteLine("First Number = {0}", firstNumber);
secondNumber = firstNumber;
Console.WriteLine("Second Number = {0}", secondNumber);
}}
Arithmetic Operators
• Arithmetic operators are used to perform arithmetic operations such as
  addition, subtraction, multiplication, division, etc.
Relational Operators
• Relational operators are used to check the relationship between two
  operands. If the relationship is true the result will be true, otherwise it
  will result in false.
Logical Operators
• Logical operators are used to perform logical operation such
  as and, or. Logical operators operates on boolean expressions
  (true and false) and returns boolean values.
• Logical operators are used in decision making and loops.
• Here is how the result is evaluated for logical AND and OR operators
Unary Operators
• Unlike other operators, the unary operators operates on a single
  operand.
Ternary Operator
• The ternary operator ? : operates on three operands. It is a shorthand
  for if-then-else statement.
• Ternary operator can be used as follows:
variable = Condition? Expression1 : Expression2;
The ternary operator works as follows:
•If the expression stated by Condition is true, the result
of Expression1 is assigned to variable.
•If it is false, the result of Expression2 is assigned to variable.
Bitwise and Bit Shift Operators
• Bitwise and bit shift operators are used to perform bit manipulation
  operations.
Compound Assignment Operators
Type Casting in C#
• Type Casting allows us to change the data type of a value to another
  data type based on specific requirements.
• In C#, which is statically typed, once a variable is declared, it cannot
  be redeclared with another type during compilation.
• There are two types of type casting in C#
• implicit type casting and
• explicit type casting.
•Implicit Casting (automatically) –
converting a smaller type to a larger type size
char -> int -> long -> float -> double
•Explicit Casting (manually) –
•converting a larger type to a smaller size type.
double -> float -> long -> int -> char
Implicit Casting
• Implicit casting is done automatically when passing a smaller size type
  to a larger size type:
• int myInt = 9;
• double myDouble = myInt;
• // Automatic casting: int to double Console.WriteLine(myInt); //
  Outputs 9 Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
• Explicit casting must be done manually by placing the type in
  parentheses in front of the value:
double myDouble = 9.78;
int myInt = (int) myDouble;
// Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
Type Conversion Methods
It is also possible to convert data types explicitly by using built-in
methods,
such as
• Convert.ToBoolean,
• Convert.ToDouble,
• Convert.ToString,
• Convert.ToInt32 (int) and
• Convert.ToInt64 (long):
using System;
namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int myInt = 10;
      double myDouble = 5.25;
      bool myBool = true;
    Console.WriteLine(Convert.ToString(myInt)); // Convert int to string
    Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double
    Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int
    Console.WriteLine(Convert.ToString(myBool)); // Convert bool to string
    }} }
o/p:10
10
5
True
C# User Input
    • We have already learned that Console.WriteLine() is used to output
      (print) values.
    • Now we will use Console.ReadLine() to get user input.
    • The Console.ReadLine() method returns a string.
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
 // Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
}}}
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
 Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
 }
}
using System;
namespace MyApplication
{ class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
}
}
}
Control Structures:
• A programming language uses control statements to control the flow
  of execution of program based on certain conditions.
The conditional statements of C#:
• if
• if-else
• if-else-if
• Nested if
• Switch
• Nested switch
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
}
// C# program to illustrate if statement
using System;
public class A{
    public static void Main(string[] args)
    {
    string name = "C#";
    if (name == "C#") {
    Console.WriteLine("c# if statement");
    }
    }
}
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
}
// C# program to illustrate if-else statement
using System;
public class B {
       public static void Main(string[] args)
       {
             string name = "sri";
             if (name == "sri") {
             Console.WriteLine("successfull");
             }
             else {
             Console.WriteLine("failed");
             }
       }
}
using System;
namespace IfElseExample
{
class Program{
     static void Main(string[] args) {
        Console.WriteLine("Please enter your age:");
        int age = int.Parse(Console.ReadLine());
        if (age >= 18)
        {
           Console.WriteLine("You are an adult.");
        }
        else
        {
           Console.WriteLine("You are a minor.");
        }
     } }}
If – else – if ladder Statement
• The if-else-if ladder statement executes one condition from multiple
  statements.
 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 }
// 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");
    }
}
using System;                                                  else if (grade >= 80)
namespace IfElseIfElseExample                                         {
{                                                                         Console.WriteLine("Your grade is B.");
    class Program                                                     }else if (grade >= 70)
    {                                                                {
        static void Main(string[] args)                                   Console.WriteLine("Your grade is C.");
        {                                                            }
                                                                     else if (grade >= 60)
            Console.WriteLine("Please enter your grade:");
                                                                     {
            int grade = Convert.ToInt32(Console.ReadLine());
                                                                          Console.WriteLine("Your grade is D.");
            if (grade >= 90)                                         }
            {                                                        else
                Console.WriteLine("Your grade is A.");               {
            }                                                             Console.WriteLine("Your grade is F.");
                                                                     } } }}
Nested – If Statement
• if statement inside an if statement is known as nested if.
• Syntax:
if (condition1)
{
// code to be executed
// if condition2 is true
if (condition2)
{ // code to be executed
// if condition2 is true
}}
// C# program to illustrate nested-if statement
using System;
class GFG {
  public static void Main(String[] args)
  {
  int i = 18;
  if (i == 18) {
  if (i < 12)
  Console.WriteLine("i is smaller than 12 too");
  else
  Console.WriteLine("i is greater than 15");
  }
  }
}
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
 }
// C# example for switch case
using System;
public class D {
        public static void Main(String[] args){
                int number = 20;
                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;
                }}}
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.
using System;
public class GFG
                                                            case 10:
{
                                                            Console.WriteLine(10);
public static void Main(String[] args)
{                                                           break;
int j = 5;                                                  case 15:
         switch (j)                                         Console.WriteLine(15);
         {
         case 5: Console.WriteLine(5);
                                                            break;
                   switch (j - 1)                           default:
                   {                                        Console.WriteLine(100);
                 case 4: Console.WriteLine(4);
                 switch (j - 2)
                                                            break;
       {                                             case
3: Console.WriteLine(3);                                                }
                 break;
                                                 }                }
                 break;                                     }
                 }
Loops
• Loops can execute a block of code as long as a specified
  condition is reached.
• Loops are handy because they save time, reduce errors, and
  they make code more readable.
• Types of loops:
• while Loop
• do-while Loop
• for loop
• foreach Loop
while Loop
• The while loop is another commonly used loop in C#.
• It continues to execute the code block as long as the specified
  condition remains true.
• Syntax:
 while (condition)
  {
     // Your code here
  }
using System;
namespace MyApplication
{
  class whileloop
  {
    static void Main(string[] args)
    {
      int count = 0;
      while (count < 5)
      {
        Console.WriteLine("Count: " + count);
        count++;
      }
      Console.ReadLine();
    }
  }
}
do-while Loop
• The do-while loop is a type of loop in C# that allows a code
  block to be executed repeatedly as long as a specified condition
  remains true.
• The unique characteristic of the do-while loop is that it
  guarantees that the code block will be executed at least once,
  regardless of the condition's initial value.
• It means the condition is checked at the end of each iteration.
• Syntax:
do
{
   //Your code here
} while (condition);
using System;
namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int i = 0;
      do
      {
        Console.WriteLine(i);
        i++;
      }
      while (i < 5);
    }
  }
}
for loop
• The for loop is one of the most commonly used loops in C#.
• It allows developers to specify the start, end, and step
  conditions explicitly, making it perfect for iterating over a
  range of values.
• Syntax:
 for (initialization; condition; iteration)
 {
   // Your Code Here
 }
using System;
namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      for (int i = 0; i < 5; i++)
      {
        Console.WriteLine(i);
      }
    }
  }
}
foreach Loop
• The foreach loop is a type of loop in C# that simplifies the
  process of iterating over elements in a collection.
• It is specifically designed for working with arrays, lists,
  dictionaries,     and    other    objects     that  implement
  the IEnumerable interface, allowing developers to access each
  element in the collection without worrying about indexing or
  managing loop counters manually.
• Syntax:
foreach (var item in collection)
 {
   // Your code here
 }
using System;
namespace MyApplication
{
  class foreachloop
  {
    static void Main(string[] args)
    {
     string[] fruits = { "Apple", "Banana", "Orange", "Mango" };
     foreach (string fruit in fruits)
     {
       Console.WriteLine("Fruit: " + fruit);
     }
     Console.ReadLine();
    }
  }
}
break Statement
• The break statement can also be used to jump out of a loop.
using System;
public class HelloWorld{
  public static void Main(string[] args)
  {
     Console.WriteLine("Using the break Statement");
         for (int i = 1; i <= 5; i++)
         {
            if (i == 3)
            {
               break; // Exit the loop when i equals 3
            }
            Console.WriteLine("Iteration: " + i);
         } }}
C# Continue
• The continue statement breaks one iteration (in the loop), if a specified condition
  occurs, and continues with the next iteration in the loop.
using System;
public class HelloWorld
{
   public static void Main(string[] args)
   {
     Console.WriteLine("Using the continue Statement");
     for (int j = 1; j <= 5; j++)
     { if (j == 3)
        {
           continue; // Skip iteration when j equals 3
        }
        Console.WriteLine("Iteration: " + j);
return statement
• It is used within functions or methods to exit the current
  function and provide a value back to the calling code.
• The return statement is crucial for controlling the flow of
  execution within methods and for providing results or values
  to the caller.
using System;
public class HelloWorld
{
  public static void Main(string[] args)
  {
     Console.WriteLine("Using the return Statement");
     int result = Multiply(5, 10);
     Console.WriteLine("Result: " + result);
  }
  public static int Multiply(int a, int b)
  {
     return a * b; // Return the product of a and b
  }
}
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.
• // C# program to illustrate the // use of goto statement
using System;
class Geeks {
    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");
        }}}
C# Preprocessor directives
• Preprocessor directives are a block of statements that get
  processed before the actual compilation starts.
• C# preprocessor directives are the commands for the
  compiler that affect the compilation process.
• All preprocessor directives begin with #, and only white-
  space characters may appear before a preprocessor directive
  on a line.
• Preprocessor directives are not statements, so they do not end
  with a semicolon (;).
The preprocessor directives available in C# are:
#define directive
• The #define directive allows us to define a symbol.
• Syntax: #define SYMBOL
#undef directive
• The #undef directive allows us to undefine a symbol.
• Syntax: #undef SYMBOL
• #if directive
• The #if directive is used to test the preprocessor expression.
• The codes inside the #if directive is compiled only if the expression
  tested with #if evaluates to true.
• Checks if a preprocessor expression is true or not
• The #if directive is used to test the preprocessor expression.
• #if directive is followed by an #endif directive.
• Syntax:
#if preprocessor-expression
code to compile<
#endif
• #endif directive
• The #endif directive is used along with #if directive to
  indicate the end of #if directive.
• Syntax:
#if preprocessor-expression-1
code to compile
#endif
#define CSHARP
using System;
namespace Directive
{
    class ConditionalDirective
    {
        public static void Main(string[] args)
        {
        #if (CSHARP)
        Console.WriteLine("CSHARP is defined");
        #endif
        }
    }
}
#elif directive
• The #elif directive is used along with #if directive which lets us
  create a compound conditional directive.
• It is used when testing multiple preprocessor expressions.
• The codes inside the #elif directive are compiled only if the
  expression tested with that #elif evaluates to true.
• Syntax:
#if preprocessor-expression-1
code to compile
#elif preprocessor-expression-2
code-to-compile
#endif
#else directive
• The #else directive is used along with #if directive.
• If none of the expression in the preceding #if and #elif (if present)
  directives are true, the codes inside the #else directive will be
  compiled.
• Syntax:
#if preprocessor-expression-1
code to compile
#elif preprocessor-expression-2
code-to-compile
#else
code-to-compile
#endif
#define CSHARP
#undef PYTHON
using System;
namespace Directive{
          class ConditionalDirective{
                       static void Main(string[] args)
                       {
                                  #if (CSHARP && PYTHON)
                                              Console.WriteLine("CSHARP and PYTHON are defined");
                                  #elif (CSHARP && !PYTHON)
                                              Console.WriteLine("CSHARP is defined, PYTHON is undefined");
                                  #elif (!CSHARP && PYTHON)
                                              Console.WriteLine("PYTHON is defined, CSHARP is undefined");
                                  #else
                                              Console.WriteLine("CSHARP and PYTHON are undefined");
                                  #endif
                       }}}
#warning directive
•The #warning directive allows us to generate a user-defined level
one warning from our code.
Syntax:
• #warning warning-message
#error directive
•The #error directive allows us to generate a user-defined error
from our code.
• Syntax:
• #error error-message
Namespaces in C#
• Namespaces are used in C# to organize and provide a level of separation of codes.
• They can be considered as a container which consists of other namespaces, classes,
  etc.
• It helps us to organize different members by putting related members in the same
  namespace.
• Namespace also solves the problem of naming conflict. Two or more classes when put
  into different namespaces can have the same name.
A namespace can have the following types as its members:
1.Namespaces (Nested Namespace)
2.Classes
3.Interfaces
4.Structures
5.Delegates
• Defining Namespace in C#       For example:
• We can define a namespace in   namespace MyNamespace
  C# using                        {
  the namespace keyword as:      class MyClass
• Syntax:                        {
namespace Namespace-Name         public void MyMethod()
{                                { System.Console.WriteLine("Creat
//Body of namespace              ing my namespace");
 }                               }
                                  }
                                 }
• Accessing Members of Namespace in C#
• The members of a namespace can be accessed using
  the dot(.) operator.
• The syntax for accessing the member of namespace is,
• Syntax: Namespace-Name.Member-Name
• Using a Namespace in C# [The using Keyword]
• A namespace can be included in a program using the using
  keyword.
• The syntax is,
• using Namespace-Name;
• Nested Namespace in C#
• A namespace can contain another namespace. It is called nested
  namespace.
• The nested namespace and its members can also be accessed using
  the dot (.) operator.
namespace MyNamespace
{
namespace NestedNamespace
{
// Body of nested namespace
}
}
C# String
In C#, a string is a sequence of characters. For example, "hello" is a string containing a sequence
of characters 'h', 'e', 'l', 'l', and 'o’.
We use the string keyword to create a string. For example,
• string str = "C# Programming";
using System;
namespace CsharpString {
 class Test {
   public static void Main(string [] args) {
    // create string
    string str1 = "C# Programming";
    string str2 = "Programiz";
    // print string
    Console.WriteLine(str1);
    Console.WriteLine(str2);
}}}
• String Operations
• C# string provides various methods to perform different operations on strings.
• Get the Length of a string
using System;
namespace CsharpString {
  class Test {
   public static void Main(string [] args) {
     // create string
     string str = "C# Programming";
     Console.WriteLine("string: " + str);
     // get length of str
     int length = str.Length;
     Console.WriteLine("Length: "+ length);
}}
}
• There are many string methods available, for ToUpper() and ToLower(), which
  returns a copy of the string converted to uppercase or lowercase:
using System;
namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      string txt = "Hello World";
      Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"
      Console.WriteLine(txt.ToLower()); // Outputs "hello world"
    }
  }
}
• Join two strings in C#:We can join two strings in C# using the Concat() method.
using System;
namespace CsharpString {
 class Test {
   public static void Main(string [] args) {
    // create string
    string str1 = "C# ";
    Console.WriteLine("string str1: " + str1);
    // create string
    string str2 = "Programming";
    Console.WriteLine("string str2: " + str2);
    // join two strings
    string joinedString = string.Concat(str1, str2);
    Console.WriteLine("Joined string: " + joinedString);
   }}}
• C# compare two strings
• In C#, we can make comparisons between two strings using the Equals() method.
  The Equals() method checks if two strings are equal or not.
• using System;
• namespace CsharpString {
• class Test {
• public static void Main(string [] args) {
    string str1 = "C# Programming";
•     string str2 = "C# Programming";
•     string str3 = "Programiz";
•     // compare str1 and str2
•     Boolean result1 = str1.Equals(str2);
•     Console.WriteLine("string str1 and str2 are equal: " + result1)
•     //compare str1 and str3
•     Boolean result2 = str1.Equals(str3);
•     Console.WriteLine("string str1 and str3 are equal: " + result2);
• }} }
• In C#, we can use string interpolation to insert variables inside a string. For string
  interpolation, the string literal must begin with the $ character.
using System;
namespace CsharpString {
  class Test {
    public static void Main(string [] args) {
     // create string
     string name = "Programiz";
     // string interpolation
     string message = $"Welcome to {name}";
     Console.WriteLine(message);
}
  }
}
What is Regular Expression in C#?
• In C#, Regular Expression is a pattern which is used to parse and
  check whether the given input text is matching with the given pattern
  or not.
• In C#, Regular Expressions are generally termed as C# Regex.
• The .Net Framework provides a regular expression engine that allows
  the pattern matching. Patterns may consist of any character literals,
  operators or constructors.
  C# provides a class termed as Regex which can be found in
  System.Text.RegularExpression namespace. This class will perform
  two things:
• Parsing the inputting text for the regular expression pattern.
• Identify the regular expression pattern in the given text.