C#
C#
An d
C#.NET
Hour 50 Setup Project Development, Installing and Un-installing the projects Page 496
              Backend tool: It acts as storage mechanism. The data related to the project
                will be stored in this backend tool. It allows us to create and store the databases.
                Ex: Oracle, SQL Server, My SQL, Sybase, DB2 etc.
      It was released by Microsoft Corporation in 2002. At this year, in the programming world,
       we have so many languages like Basic, COBOL, Pascal, Fortran, C, C++, VB, VC++ etc.
       But if you observe these languages, each and every language is having its own
      Language: It acts as interface (mediator) between the programmer and the system. It
       offers some rules and regulations for writing the programs. It also offers some library,
       which is required for writing the programs. Obviously, the collection of programs is called
       as ―Software‖.
         .NET Framework) provides support for 3 Microsoft developed languages and several
         other languages from other vendors.
Modules of .NET
             It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for server
              side logic implementation.
             It requires a .NET language (like C#, VB.NET, VC++.NET etc.) for logic
              implementation.
1. Console Applications
           These applications contains similar user interface to the operating systems like MS-
            DOS and UNIX.
 Doesn‘t contain any graphical features like mouse pointer, colors, fonts, buttons etc.
 Offers graphical features like mouse pointer, colors, fonts, buttons, text boxes etc.
 Examples:
i. Windows Time.
iv. Database services like SQL Server, My SQL and Oracle etc.
etc.
        To see the all the installed windows services on the system, click on ―Start‖ –
         ―Control Panel‖ – ―Administrative Tools‖ – ―Services‖.
        Some other web sites are offering general purpose services that can be used by
         anybody like E-Mail, Search Engines, and Blogs etc.
        So, there is much demand for these applications in modern software development
         industry.
        In .NET Framework, the web sites can be developed using the technology called
         ASP.NET.
 Ex:
i. http://www.yahoo.com/
ii. http://www.google.co.in/
iii. http://www.orkut.com/
iv. http://www.hotmail.com/
        The web services are used to implement ―SOA‖ (Service Oriented Architecture) in
         web applications.
 Examples:
i. Online shopping requires credit card authentication, from back web site.
   7. WPF Applications
        WPF stands for Windows Presentation Foundation.
        These Applications support more advanced graphical features like shapes, object
         transformation, brushes etc.
           C
                (For General Programming Experience)
           SQL
                (For writing the database queries in ADO.NET)
           HTML
                (For web page designing in ASP.NET)
Promises by Microsoft:
       Multiple platforms: The system runs on a broad range of computers, from servers and
        desktop machines, smart phones and cell phones.
       Industry standards: The system uses industry standard communication protocols,
        such as XML, HTTP, SOAP, and WSDL.
       Security: The system can provide a much safer execution environment, which can‘t be
        hacked or robbed by others.
.NET Framework 1.0 1.0.3705.0 Feb 13, 2002 Visual Studio.NET 2002
.NET Framework 1.1 1.1.4322.573 April 24, 2003 Visual Studio.NET 2003
.NET Framework 2.0 2.0.50727.42 November 17, 2005 Visual Studio 2005
.NET Framework 3.0 3.0.4506.30 November 06, 2006 [No Visual Studio]
.NET Framework 3.5 3.5.21022.8 November 19, 2007 Visual Studio 2008
.NET Framework 4.0 4.0.30319.0 April 12, 2010 Visual Studio 2010
dvantages of .NET
      Supports multiple languages like VC#, VB.NET, VC++.NET, VJ#.NET etc., so that the
       programmer can write the code in his/her interested language.
      Offers more secured environment never before.
      Offers flexible data access with ADO.NET.
      Supports to develop windows services and web services, which are necessary to
       handle in the live projects in the modern programming world.
      Supports to develop applications for small devices like PDA‘s, smart phones, mobile
       phones etc.
      Offers ―Partial platform independency‖, because it supports to run the .NET
       applications on Windows and LINUX platforms with Mono Tool.
      Offers easier and faster UI design (with drag and drop technique), when compared with
       the languages like Java.
                                           Similarities
      Sl.
                                             .NET and Java
      No
            Both of these support to develop console applications, windows applications, web
       1
            sites, web services etc.
            Both use their own intermediate language. Java calls it as ―byte code‖ and .NET
       2
            calls it as ―MSIL‖.
       3    Both are Object oriented programming languages.
       4    Both support Remoting.
       5    Both support multi-threading.
       6    Both support web related languages like Java Script, XML, CSS etc.
       7    Both support the recent web development technology like AJAX.
            Both support ―Garbage collection‖, which automatically clears the un-used
       8
            memory.
            Both support to develop the applications for small devices like PDA‘s, mobile
       9
            phones, smart phones etc.
      10    Both offer better security features in their own style.
                                           Differences
      Sl.
                            .NET                                         Java
      No
            It is cost effective. Costs more than     It is open source product, which can be
       1
            $700 (nearly Rs. 35,000)                  freely downloaded on the Internet.
       2    It‘s a collection of multiple languages   It‘s itself is a language.
            It‘s partially platform independent (as
            .NET applications can run on
       3                                              It‘s fully platform independent.
            Windows and LINUX operating
            systems)
            Offers IDE as Visual Studio by            Doesn‘t offer any IDE. But other IDE‘s by
       4
            Microsoft.                                other vendors such as Eclipse etc.
            Offers easiest and fastest application    Requires much time for the application
       5    development, which indirectly reduces     development, which indirectly increases
            the cost of the software.                 the cost of the software.
            Designing the UI is very much easy        UI Design requires much programmer‘s
       6
            with ―Drag and Drop‖ technique.           effort and stress.
                                                      AJAX is implementation is much time
       7    AJAX is implementation is much easy.      taking process, requires much code to
                                                      write.
      .NET Framework: This is the general version, required to run .NET applications on
       Windows operating system.
      .NET Mono Framework: This is required to run .NET applications on other operating
       systems like UNIX, LINUX and Solaris etc.
      .NET Compact Framework: This is required to run .NET applications on other devices
       like PDA (Personal Digital Assistants), Mobile phones and Smart phones.
You can see the .NET Framework Architecture in the following diagram.
Naming Convention
System
Windows Web Drawing Linq Xml Data Threading IO Text Speech Runtime
                                                                                                Configuration     Remoting
 Forms             UI         Printing                OleDb        SqlClient
HtmlControls WebControls
       The Common Language Runtime (CLR) is the agent that manages your .NET
        applications at execution time. In other words, CLR is the completely responsible
        component of .NET Framework that is responsible to manage the .NET applications at
        run time.
       In other words, The Common Language Runtime (CLR) is the virtual machine in the
        .NET Framework.
       It provides core services such as memory management, thread management,
        exception handling, security and resource management.
       A .NET application is compiled into a ―bytecode‖ format known as MSIL (Microsoft
        Intermediate Language). The MSIL bytecode allows .NET applications to be portable
        (at least theoretically) to other platforms because the application is compiled to native
        code only during runtime.
       During execution, the CLR‘s JIT (just - in - time) compiles the bytecode into the
        processor‘s native code and executes the application.
       In .NET, when an application is compiled, into a bytecode called MSIL. That MSIL code
        is stored in an assembly. The assembly is contained in one or more PE (portable
        executable) files and may end with an EXE or DLL extension.
       The assembly contents are:
             Byte code — The code in MSIL language.
           Security Information — Information about the users / user types, who can
          Private Assemblies: The private assemblies are simple types. An assembly that can
           be used only within a software application is called as ―Private assembly‖. This type of
           assemblies contains ―.exe‖ file extension.
          Shared Assemblies: An assembly that can be used by one or more software
           applications is called as ―Shared Assemblies‖. This type of assemblies contains ―.dll‖
           (dynamic linking library) file extension.
Example:
                To get a better idea of a MSIL file and its content, take a look at the following
example, which has two console applications. One is written in C# and the other is written in
VB.NET.
          The following C# code displays the “Hello, World” message in the
          console window:
             using System;
             using System.Collections.Generic;
             using System.Linq; using
             System.Text; namespace
             HelloWorldCS
             {
                     class Program
                     {
                              static void Main(string[] args)
                              {
                                       Console.WriteLine(―Hello, World!‖);
                                       Console.ReadLine();
                              }
                     }
             }
          The following VB.NET code displays the “Hello, World” message in the
          console window:
              Module Module1
                     Sub Main()
                              Console.WriteLine(―Hello, World!‖)
                              Console.ReadLine()
                     End Sub
              End Module
Conclusion: The Main method of the VB.NET MSIL looks very similar to that of the C#.NET‘s
MSIL program.
The important thing to note here is that regardless of the language you use to develop your .NET
applications, all .NET applications are compiled to the MSIL bytecode as this example shows.
Note: MSIL can also be called as IL (Intermediate Language) and CIL (Common Intermediate
Language).
Assembly (.exe)
MSIL Code
                              Just-in Time
                               Compiler
                       01010101010111010
                       01010101010111010
                       01010101010111010
                       01010101010111010
Operating System
3.   Memory Manager
        The ―Memory Manager‖ component of CLR, allocates necessary memory for the
         variables and objects that are to be used by the application.
4.   Garbage Collector
        This component of CLR de-allocates or cleans-up the un-necessary memory of the
         application, after usage automatically.
        Instead, in older languages such as C/C++ this kind of component is not available so
         that the programmer should free-up the memory explicitly using some code.
5.   Exception Manager
        An exception means ―Run time error‖.
        This component redirect the processor to execute the ―catch‖ block or ―finally‖ block,
         whenever an exception is occurred at run time.
        We can learn how to write these catch and finally blocks in C#.NET and VB.NET
         languages later.
         Processor:
                Minimum: P-IV
                Recommended: Higher than P-IV
         RAM:
                Minimum: 512 MB
                Recommended: 1 GB (or above)
         OS:
                MS Windows
                 (XP / 2003 / Vista / 2008 / Windows 7)
         Processor:
              Minimum: P-IV
              Recommended: Higher than P-IV
         RAM:
              Minimum: 512 MB
              Recommended: 1 GB (or above)
         OS:
              MS Windows
                  (XP Service Pack 3 / 2003 / Vista / 2008 / Windows 7)
      Initially, the ―Visual Studio 2010‖ will be opened along with ―Start Page‖.
      The start page is nothing but the welcome page, which contains
               Logo: A logo of ―Microsoft Visual Studio 2010‖ on the top of the start page.
              Recent Projects: List of most recently opened projects. If you click on any one,
                the project will be opened immediately.
               Get started / Guidance and Resources / Latest News: Headlines of visual
                studio help for .NET programmers. If you click on any one head line, online help
                will be opened (if Internet connection is available).
             Build: Compilation of entire .NET Project (all the files will be compiled at-a-
              time).
class class1
int mydatamember;
void mymethod()
             Namespace: It‘s nothing but a collection of classes. It may also contain sub
              namespaces. A project may require implementing at least one or more classes.
              Any class can‘t be defined individually, without a namespace. In .NET, all of the
              classes related one application should be defined with a user defined namespace.
                        namespace MyApplication
                        {
                              class class1
                              {
                              }
                              class class2
                              {
                              }
                        }
In the above screen, you can see an empty form created automatically, named as ―Form1‖.
You can observe the project directory structure according to our previous example.
Note: First, recollect the project name, project location and solution name from previous
example.
    bin: This folder contains the ―EXE‖ file after compiling the project.
    obj: This folder cntains the temporary files of the project, while compilation.
    Properties: This folder contains necessary files that contain information about the
       settings and resources related to the project.
    WindowsFormsApplication1.csproj (Project File): This file contains the information
       about all the files related to the project; When you double click on it, the project will be
       opened in Visual Studio.
    Form1.cs: This file contains the executable code of ―Form1‖.
    Form1.Designer.cs: This file contains the code related to the design of Form1.
    Program.cs: This file contains the code of ―Program‖ class with Main() method.
    1) Menu Bar: This bar contains the available menus in Visual Studio like ―File‖, ―Edit‖,
         ―View‖ and ―Project‖ etc.
    2)   Tool Bars: There are several toolbars in Visual Studio, which contain frequently used
         options in Visual Studio.
    3) Tabs: Displays tabs; just click to open required tab.
    4) Form designer: Used to view and edit the visual design of the form.
    5) Code Window: This is where you write actual programming of your application. You
         can switch to this view, by right click on the ―form designer‖ and choosing ―View Code‖
         (or) by pressing F7 key on the keyboard.
File Extensions in C#
      Project File Extension: ―.csproj‖ (means C Sharp Project)
      Code File Extension: ―.cs‖ (means C Sharp)
Basic Terminology in C#
      Statement: It‘s a line in the program.
                --------------;
      Keyword: It‘s a reserved word, which has some pre-defined meaning. Ex: void, class,
       struct, using, while, do, for, if, else etc.
      Data type: It‘s a keyword, which specifies the type of the data that you are going to
       store in a variable or constant. Ex: int, float, char, string etc.
      Variable: It‘s a named memory location, which contains a particular type value and
       which value can be changed during the program execution.
data_type variable_name;
      Constant: It‘s a fixed value, which value can‘t be changed during the program
       execution. Ex: 1, 10, ‗a‘, ―abcd‖.
      Operator: It‘s a symbol, which performs some operation. Ex: +, -, *, /, ++ etc.
      Condition: It‘s an expression, which can have a result (True / False).
                    class <classname>
                    {
                       //fields
                       //properties
                       //methods
                    }
      Object: It‘s an instance to the class. The memory will be allocated for the object only,
       not for the class. It is able to access the members of the class. An object can be created
       as follows:
      To run the application, simply press ―F5‖ key on the keyboard. Then the application will
       be executed and output will be as follows.
Main() method
1. Importing section:
    This section contains importing statements that are used to import (include or link) the
       .NET Framework Class Library (FCL).
    This is most similar to the ―include‖ statements in ―C‖ language.
    Syn:
               using namespace;
    Note: If the required namespace is a member of another namespace, we have specify
       the parent and child namespaces separated with ―.‖ (dot).
    Ex:
               using System;
2. Namespace declaration:
    Here, a user define namespace is to be declared.
    Rule: In .NET applications, all the classes related to the project should be declared in
       one namespace.
       Syn:
               namespace namespacename
               {
               }
    Generally, the namespace name will be same as ―Project‖ name.
2. Class declaration:
    This is to declare the startup class of the project.
      In every .NET application (like Console and Windows Application), there should a startup
       class. In these applications, the startup class name should be ―Program‖. You can‘t
       change it.
    A startup class nothing but a class, which contains Main() method.
       Syn:
               class classname
               {
3. Main() method:
    As you know already in C/C++ languages, the Main() method is the Starting Execution
       Point of the application.
    When the application is executed, the Main() method will be executed first.
    This method contains the main logic of the application.
1)   Keywords
      You can observe the available keywords in C#.
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace ConsoleClassDemo
 {
   /*Demo on Console Class*/
   class Program
   {
      static void Main(string[] args)
      {
         //Output demo
         System.Console.WriteLine(".NET Framework is:");
         System.Console.Write("C#.NET+");
         System.Console.Write("VB.NET+");
         System.Console.WriteLine("ASP.NET");
             //Input demo
             string name;
             System.Console.Write("\nEnter your name: ");
             name = System.Console.ReadLine();
             System.Console.Read();
         }
     }
}
Output:
You can observe the data types, memory size and ranges inthe following table.
      Note: When we declare any variable, it should be assigned to a value before its usage.
            Otherwise, it causes a compile time error.
      Note: ―+‖ is known as ―concatenation‖ operator, which can concatenate two similar or
            different types of values as a ―string‖.
     using   System;
     using   System.Collections.Generic;
     using   System.Linq;
     using   System.Text;
     namespace Variables
     {
       class Program
       {
          static void Main(string[] args)
          {
             int n = 4561;
             Console.WriteLine(n);
             decimal a, b, c;
             double d1, d2=45.123, d3;
             Console.WriteLine("d2 value is " + d2);
             string s1;
             bool b1 = true;
             Console.WriteLine(b1);
             string Country = "India";
             int States = 28;
             Console.WriteLine("Our country is " + Country + ". It has " + States + " states.");
Output:
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace EscapeSequenceCharacters
 {
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("This is first line\nThis is second line\nThis is third line.");
Output:
 8)      Constants
            Constants look just like variables, but concept wise, they differ from variables.
            The main differences between constants and variables are:
                  The value of constants can‘t be changed during the program execution time.
                  The constants should be initialized at the time of its declaration.
            To declare constants,
                   Syn: const datatype constantname = value;
                   Ex: const int x=100;
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace Constants
 {
   //An application, that calculates area of circle
   class Program
   {
Output:
      Implicit Casting
          Implicit casting is possible in the following cases.
          Explicit Casting
             Explicit casting should be performed in the following cases:
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace Casting
  {
    class Program
    {
       static void Main(string[] args)
       {
Output:
              System.Convert.ToSByte(value);
                            Converts the value into ―sbyte‖ type.
              System.Convert.ToByte(value);
                            Converts the value into ―byte‖ type.
              System.Convert.ToInt16(value);
                            Converts the value into ―short‖ type.
              System.Convert.ToUInt16(value);
                            Converts the value into ―ushort‖ type.
              System.Convert.ToInt32(value);
                            Converts the value into ―int‖ type.
            System.Convert.ToInt64(value);
                         Converts the value into ―long‖ type.
            System.Convert.ToUInt64(value);
                         Converts the value into ―ulong‖ type.
            System.Convert.ToSingle(value);
                         Converts the value into ―float‖ type.
            System.Convert.ToDouble(value);
                         Converts the value into ―double‖ type.
            System.Convert.ToDecimal(value);
                         Converts the value into ―decimal‖ type.
            System.Convert.ToChar(value);
                         Converts the value into ―char‖ type.
            System.Convert.ToString(value);
                         Converts the value into ―string‖ type.
            System.Convert.ToBoolean(value);
                         Converts the value into ―bool‖ type.
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace ConversionMethods
 {
   class Program
   {
      static void Main(string[] args)
      {
Output:
IMP Note:
            By default, C# recognizes all the integer constants as the type of ―int‖.
            In the same way, C# recognizes all the floating point constants as the type of
             ―double‖.
            There is no ―ToObject()‖ method to convert a value into ―object‖ data type.
 namespace BoxingAndUnboxingDemo
 {
   class Program
   {
      static void Main(string[] args)
      {
         int x = 10;
             //boxing
             Object obj;
             obj = x;
             Console.WriteLine(obj);
             //un-boxing
             x = Convert.ToInt32(obj);
             Console.WriteLine(x);
             Console.Read();
         }
     }
 }
Output:
          Strong Rule to follow:          Multiple variables with same name within the same scope
           can‘t be declared anywhere.
12) Operators
       C# supports different kinds of operators.
           Assignment operator
            =
           Arithmetical / Mathematical operators
            +, -, *, /, %
           Relational operators
            ==, !=, <, >, <=, >=
       Comment operators
        //xxxxxxxxxxxxxx
(or)
        /* xxxxxxxxxxx
          xxxxxxxxxxx
          xxxxxxxxxxx*/
       Concatenation Operator
        +
       Conditional operator
        ?:
                     if-else
                                if (condition)
                                {
                                          ----;
                                          ----;
                                }
                                else
                                {
                                          ----;
                                          ----;
                                }
                     else-if
                                if (condition)
                                {
                                          ----;
                                          ----;
                                }
                                else if (condition)
                                {
                                          ----;
                                          ----;
                                }
                                else if (condition)
                                {
                                          ----;
                                          ----;
                                }
                                else
                                {
                                          ----;
                                          ----;
                                }
          switch-case
                   switch (variable)
                   {
                            case value1: ---------; break;
                            case value2: ---------; break;
                            case value3: ---------; break;
                            case value4: ---------; break;
                            default: ---------; break;
                   }
          break
                   for loop / while loop / do-while loop
                   {
                            ----------;
                            ----------;
                            break;
                            ----------;
                   }
          goto
                   ----------;
                   ----------;
                   ----------;
                   goto labelname;
                   ----------;
                   ----------;
                   labelname:
                   ----------;
                   ----------;
                   ----------;
          do-while
                   initialization;
                   do
                   {
                              ----------;
                              ----------;
                              ----------;
                              Increment / decrement;
                   } while(condition);
Note: You can also implement nested loops as you implemented in C/C++.
14) Enumerations
        An enumeration is a collection of constants. That means you can create your own set of
         named constants by using enumerations.
        Each constant will have a name with an integer value.
        Syntax for Enumeration Declaration:
                 public enum enumname
                 {
                         Constant1 = value1, Constant2 = value2, Constant3 = value3
                 }
        Syntax for usage
                 enumname.constantname
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace EnumerationDemo
 {
   public enum Months
   {
      January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7,
 August = 8, September = 9, October = 10, November = 11, December = 12
   }
   class Program
   {
Output:
15) Arrays
        An array is the collection of similar type of values.
        Each value in the array is to be called as an element.
        The total no. of array elements is called as ―Array size‖.
        Implementation of Arrays:
            Single Dimensional Arrays:
                Array declaration:
                                                                                 Single-dim
                    Without initialization:
                                                                                    array
                            datatype[] arrayname = new datatype[size];
                    With initialization:
                            datatype[] arrayname = {val1,val2,val3,…..};
                    With initialization:
                            datatype[,] arrayname = {{val1,val2,…}, {val1,val2,…},…};
 namespace ArrayDemo
 {
   //Demo on Single-Dim Array.
   class Program
   {
      static void Main(string[] args)
      {
         //read the no. of students
         int n;
         Console.Write("Enter no. of students: ");
         n = Convert.ToInt32(Console.ReadLine());
            //calculate results
            for (int i = 0; i < n; i++)
            {
Output:
 namespace MultiDimArrays
 {
   //Demo on Multi-Dimensional Arrays
   class Program
   {
      static void Main(string[] args)
      {
         //Single dimensional arrays int[] x = { 10, 20,
         30, 40}; Console.WriteLine("Single dimensional
         array:"); for (int i = 0; i < x.Length; i++)
             Console.Write(x[i] + ", ");
         //Double dimensional arrays
         int[,] y = { {10, 20}, {30, 40}, {50, 60} };
         Console.WriteLine("\n\nDouble dimensional array:");
         for (int i = 0; i < 3; i++)
         {
             for (int j = 0; j < 2; j++)
                Console.Write(y[i, j] + " ");
             Console.WriteLine();
         }
         //Multi dimensional arrays
         int[, ,] z = { { { 5, 10 }, { 15, 20 } }, { { 25, 30 }, { 35, 40 } }, { { 45, 50 }, { 55, 60 } } };
         Console.WriteLine("\nMulti dimensional array:");
         for (int i = 0; i < 3; i++)
         {
             for (int j = 0; j < 2; j++)
             {
                for (int k = 0; k < 2; k++)
                    Console.Write(z[i, j, k] + " ");
                Console.WriteLine();
             }
             Console.WriteLine();
         }
         Console.Read();
      }
   }
 }
Output:
“foreach” Loop
         One of the most common usages of the ―for‖ loop is to iterate through a collection of
          values (array).
         C# offers a simplified and easier syntax of for loop called ―foreach loop‖, designed only
          for such kind of array iterations.
         Syntax:
                foreach (datatype variable in arrayname)
                {
                        -----------;
                        -----------;
                }
         In the above syntax, the loop will be executed once for each value in the array. For
          every iteration, the values of the array will be assigned to the variable.
         For example, you take the following for loop.
                int[] nums = { 10, 20, 30};
                for (int i = 0;i < nums.Length; i++)
                {
                          Console.WriteLine(nums[i]));
                }
         You can re-write the above example with ―foreach‖ syntax as follows:
                int[] nums = { 10, 20, 30};
                foreach (int n in nums)
                {
                        Console.WriteLine(n);
                }
Note: The ―arrayname.Length‖ property gets the size of the array. We discuss about the ―Array‖
class in future.
Jagged Arrays
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace JaggedArraysDemo
  {
    class Program
    {
       static void Main(string[] args)
       {
          int[][] a = new int[3][];
          a[0] = new int[] { 1, 2 };
          a[1] = new int[] { 3, 4, 5, 6, 7, 8 };
          a[2] = new int[] { 9, 10, 11 };
             Console.Read();
         }
     }
 }
Output:
             Now, locate the ―bin‖ folder of the required application, by using the following
              commands. For example, let us imagine that there is a project named
              ―ConsoleApplication1‖ in ―D:‖ drive.
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace ArgsDemo
 {
   class Program
   {
      static void Main(string[] args)
      {
         if (args.Length > 0)
         {
             Console.WriteLine(args.Length + " arguments found. Those are:");
             for (int i = 0; i < args.Length; i++)
                Console.WriteLine(args[i]);
         }
         else
             Console.WriteLine("No arguments found...");
         Console.Read();
      }
   }
 }
Output:
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace MultipleMainMethods
  {
    class Program
    {
       static void Main(string[] args)
       {
          Console.WriteLine("This is the Main() method in Program class.");
          Console.Read();
       }
    }
    class MySample
    {
       static void Main(string[] args)
       {
          Console.WriteLine("This is the Main() method in MySample class.");
          Console.Read();
       }
    }
  }
 When this program is compiled, the compiler shows 2 compile time errors.
       It‘s because, two Main() methods are found in MySample class and Program class;
         So that the compiler can‘t understand which Main() method is to be used as exact
         entry point.
       To specify the required entry point, we have to change ―Startup Object‖ option in the
         project properties.
       To open the project properties, click on ―Project‖ menu – ―Properties‖.
       Then the project properties will be opened. Now, observe the ―Startup Object‖ option.
       The ―Startup Object‖ option contains two options.
             (Not Set)
             MultipleMainMethods.Program
                        (―MultipleMainMethods‖ is the project name).
       Whenever it is set to “(Not Set)”, C# compiler automatically detects the Main()
         method, where it is exists. This is the default value in the ―Startup object‖ option. But
         this fails whenever multiple Main() methods are defined.
       Now you have to select the required class that contains the desired Main() method as
         entry point.
          Property:
                   It‘s an extension to the field, which automatically performs the specified
                    code, whenever its value is changed.
          Object:
                   It‘s an instance of the class.
                   It‘s required because, no memory will be allocated for the class, so that
                    you can‘t store any data and you can‘t call any operation.
                   It is similar to ―structure variables‖, which is declared for the ―structure‖.
                   The actual memory will be allocated for the object, which includes with
                    all the data members.
                   The object can access the members that are defined in the class.
class employee
         employee id                                              Object1
         name
         phone
         address
         salary                                                   Object2
         tax
         net_salary
         getdetails()
         displaydetails()
                                                                  Object3
         calculate_net_salary()
                        By default, the objects are isolated. That means there is no any relation
                         between the data stored in one object and another object.
Object1 Object2
Object3
                            employee id = 103
                            name = pqr
                            phone = 7839403200
                            address = chennai
                            salary = 10380
                            tax = 1270
                            net_salary = 9110
C++ (vs) C#
       In C++, the class definition syntax should end with ; whereas in C#, it‘s not required.
       In C++, we have private section, public section and protected section separately. But in
        C#, there no such kind of sections and the access modifier should be specified for each
        member of the class.
       In C++, it is not possible to initialize the data members in the class definition. But
        whereas in C#, it is possible.
       In C++, there is provision to declare the member functions inside the class and then
        write the definitions of those member functions outside of the class. But in C#, there is
        no such kind of provision. The methods should be defined inside of the class definition
        only.
       In C++, 3 access modifiers (private, protected and public) only supported. But in C#, 5
        access modifiers are supported (private, protected, public, internal, protected internal).
2) Data Abstraction
4) Polymorphism
5) Inheritance
2) Data Abstraction:
Access Modifiers:
 = Accessible
Rule to follow: According to the nature of data hiding, it recommends us to define the fields as
―private members‖ and methods as ―public members‖.
So that finally the object can perform only the allowed operations (defined by the methods);
can‘t perform other operations.
4) Polymorphism:
                 2) Run-time Polymorphism:
                                  The decision can be made at run time.
                                  This can be implemented with two concepts:
                                       i)   Templates / Generics: You can pass any type of
                                            value as an argument to a method.
                                       ii) Interfaces: Contains method declarations only,
                                            doesn‘t contain method definitions.
5) Inheritance:
            The process of creating a new class that derives all the features of another
             existing class is called as ―Inheritance‖.
            In other words, we can extend the features of a class.
Inherit
            class classname
            {
                //fields
                //properties
                //methods
            }
Note 2: The functional modifiers are static, readonly, virtual, override. We cover about these
modifiers also in further hours.
                 //memory allocation
                      objname = new classname();
(or)
obj.field
obj.property
obj.method()
 namespace OOPDemo
 {
   class test
   {
      //fields
      public string str = "windows";
      public int num = 90251;
        //methods
        public void ReverseString()
        {
           string r = "";
           int i;
           int len = str.Length;
           for (i = len - 1; i >= 0; i--)
              r = r + str[i];
           Console.WriteLine("Reversed string is: " + r);
        }
             //access fields
             Console.WriteLine(t.num);
             Console.WriteLine(t.str);
             //access methods
             t.ReverseString();
             t.ReverseNumber();
             Console.Read();
         }
     }
 }
Output:
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace DataHidingDemo
 {
   class MyMath
   {
      //private fields
      private int x, y;
         //public methods
         public void SetValues(int FirstVal, int SecondVal)
         {
            x = FirstVal;
            y = SecondVal;
         }
mm.SetValues(10, 3);
             mm.Addition();
             mm.Subtraction();
             mm.Multiplication();
             mm.Division();
             Console.Read();
         }
     }
 }
Output:
                                      ReadOnly Fields
        The ―ReadOnly‖ members are just like constants according to the objects.
        The ―readonly‖ modifier can be used for fields only.
        Once you initialize the value of ―ReadOnly data members‖, the object can‘t change that
         value, but it can access the value.
        Note: The read only field‘s values can be changed inside of the class only.
        To declare the read only fields:
                 Syntax: access_specifier readonly data_type variable_name = value;
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace ReadOnlyDataMembersDemo
{
  class Sample
  {
     //read only data member
     public readonly string CompanyName = "Wipro";
  }
  class Program
  {
     static void Main(string[] args)
     {
        Sample s = new Sample();
        Console.WriteLine(s.CompanyName);
        //s.CompanyName = "TCS"; // is not allowed bcoz it is the readonly member.
        Console.Read();
     }
  }
}
Output:
                                   “Ref” Parameters
       The reference parameters are similar to the normal parameters.
      The only difference between the normal parameters and reference parameters is: When
        the value is changed in the reference parameter, would automatically affect
        the actual parameter in the calling portion.
       Implementation: Use ―ref‖ keyword in calling portion and also in method definition.
       Rule: The actual parameter at the calling portion should be a variable and can‘t be a
        constant.
       This is just like ―Call by reference‖ concept in C/C++.
  namespace RefParameterDemo
  {
    class SampleClass
    {
       public void FirstMethod(int x, int y)
       {
          x++;
          y++;
       }
       public void SecondMethod(int x, ref int y)
       {
          x++;
          y++;
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          int a = 10, b = 20;
          SampleClass sc = new SampleClass();
          Console.WriteLine(a + ", " + b);
          sc.FirstMethod(a, b);
          Console.WriteLine(a + ", " + b);
          sc.SecondMethod(a, ref b);
          Console.WriteLine(a + ", " + b);
          Console.Read();
       }
    }
  }
Output:
“Out” Parameters
  using    System;
  using    System.Collections.Generic;
  using    System.Linq;
  using    System.Text;
  namespace OutParametersDemo
  {
    class Test
    {
       public string GetBigAndSmall(string s1, string s2, out string small)
       {
          string big;
          if (s1.Length > s2.Length)
              big = s1;
          else
              big = s2;
               return (big);
           }
       }
         class Program
         {
            static void Main(string[] args)
            {
               Test t = new Test();
               string s1 = "dotnet";
               string s2 = "framework";
               string small; //no need of initialization
               string big;
               big = t.GetBigAndSmall(s1, s2, out small);
               Console.WriteLine("Small string: " + small);
               Console.WriteLine("Big string: " + big);
               Console.Read();
            }
         }
 }
Output:
                                      “this” Keyword
           This is similar to ―this pointer‖ in C++.
           It represents current working object.
          It is used to access the members of current working object.
                    this.field
                    this.property
                    this.method()
           Current object: The object, with which object, the method is called.
           “this” keyword can‘t be used in the static methods, because static methods doesn‘t have
            current object.
  namespace ThisKeywordDemo
  {
    class Sample
    {
       //fields
       public int n = 100;
            //methods
            public void Increment()
            {
               int n = 10; //incrementation value
               this.n = this.n + n;
            }
          }
          class Program
          {
             static void Main(string[] args)
             {
                Sample s = new Sample();
                Console.WriteLine(s.n);
                s.Increment();
                Console.WriteLine(s.n);
                Console.Read();
             }
          }
  }
Output:
                                   Named Parameters
           This feature is introduced in C#.NET 4.0.
           This is used to pass the arguments to the method, with those names.
  namespace NamedParametersDemo
  {
    class User
    {
       //fields
       public string FirstName;
       public string LastName;
          //methods
          public void SetUserName(string FirstName, string LastName)
          {
             this.FirstName = FirstName;
             this.LastName = LastName;
          }
              Console.Read();
          }
      }
  }
Output:
   2. Static Members:
               If you are using ―static‖ keyword while the declaration of a field / property or a
                method, then it can be called as ―Static member‖.
              The main feature of non-static member is - it will not be bounded with the any
                object. It is individually accessible with the class name. In other words, the static
                members are accessible directly, without even creating one object also.
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace StaticMembersDemo
{
  class Student
  {
     //non-static data members
     public string StudentName;
     public string Course;
        //non-static methods
        public void SetStudentDetails(string StuName, string Cou)
        {
           StudentName = StuName;
           Course = Cou;
        }
           //static methods
           public static void DisplayCollegeDetails()
           {
              Console.WriteLine(CollegeName);
              Console.WriteLine(CollegeAddress);
           }
       }
       class Program
       {
          static void Main(string[] args)
          {
             //access static members
             Student.DisplayCollegeDetails();
               Console.Read();
           }
       }
  }
Output:
                                     Static Classes
       A static class can be created using a keyword called ―static‖ used at the class definition.
       A static class can contain only static members (static data members and static methods).
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace StaticClassesDemo
{
  static class Sample
  {
     public static string SampleStaticMember = "This is my static data member";
     public static void SampleStaticMethod()
     {
         Console.WriteLine("This is my static method.");
     }
  }
  class Program
  {
     static void Main(string[] args)
     {
         Console.WriteLine(Sample.SampleStaticMember);
         Sample.SampleStaticMethod();
         Console.Read();
     }
  }
}
Rules of Constructors:
Types of Constructors:
   i)   Implicit constructor:
                A constructor, offered by the compiler implicitly is called as "Implicit constructor".
Models of Constructors:
  i)    Default constructor:
                 It's a constructor, with no arguments.
  ii) Parameterized constructor:
                 It's a constructor, with one or more arguments.
Constructor Implementation:
  i)     Default constructor:
                  public classname()
                  {
                          ---------------;
                          ---------------;
                  }
Destructor
       It is also a method of a class, which is having some special features just like constructor.
       But it can be called automatically by the compiler, at "object destruction time".
   Object destruction time means, the time of clearing of memory i.e. allocated for the
        object.
Destructor Implementation:
         ~classname()
         {
             ----------;
             ----------;
             ----------;
         }
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace ConstructorsAndDestructorsDemo
 {
   class Student
   {
      //private fields
      private int StudentID;
      private string StudentName;
         //public method
         public void Display()
         {
            Console.WriteLine(StudentID + ", " + StudentName);
         }
          //parameterized constructor
          public Student(int StudentID, string StudentName)
          {
             this.StudentID = StudentID;
             this.StudentName = StudentName;
          }
          //destructor
          ~Student()
          {
             Console.WriteLine("This is destructor...");
          }
      }
      class Program
      {
         static void Main(string[] args)
         {
            //invoke default constructor
            Student s1 = new Student();
            s1.Display();
              Console.Read();
          }
      }
  }
  namespace ObjectInitializerDemo
  {
    class Department
    {
       //fields
       public int DeptNo;
       public string DeptName;
       public string Location;
       //methods
       public void Display()
       {
          Console.WriteLine("Department No: " + DeptNo);
          Console.WriteLine("Department Name: " + DeptName);
          Console.WriteLine("Location: " + Location);
       }
    }
    class Program
    {
        static void Main(string[] args)
        {
           Department d = new Department() { DeptNo=10, DeptName="Sales",
  Location="Hyderabad" };
           d.Display();
           Console.Read();
        }
    }
  }
Output:
     Syntax:
               static classname()
               {
                       //some code
               }
     Rules:
          1. Static constructors can‘t contain any access modifiers.
          2. Static constructors can‘t be defined with arguments.
          3. Static constructors can‘t access the non-static data members.
namespace StaticConstructorsDemo
{
  class MyCollege
  {
     //static fields
     public static string CollegeName;
     public static string Address;
       //static constructor
       static MyCollege()
       {
          CollegeName = "ABC College of Technology";
          Address = "Hyderabad";
       }
     }
     class Program
     {
        static void Main(string[] args)
        {
           Console.WriteLine(MyCollege.CollegeName);
           Console.WriteLine(MyCollege.Address);
           Console.Read();
        }
     }
}
                                                                                    Page 111 of 553
Output:
                             Method Overloading
        Def: Method overloading is nothing but writing multiple methods with same name and
          with different arguments.
         To overload methods, you should follow the below rules.
              1. All of the overloaded methods name should be same.
              2. Any difference between the method arguments should be maintained. The
                  difference may be in no. of arguments or the data types of arguments.
         Finally, when you call the overloaded method, automatically compiler takes the decision
          that ―which method is to be called‖, based on the arguments that you are passing.
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace MethodOverloadingDemo
  {
    class OverloadTest
    {
       public double GetSimpleInterest(double p, double n, double r)
       {
          double si;
          si = (p * n * r) / 100;
          return (si);
       }
       public double GetSimpleInterest(double p, double n)
       {
          double si;
          si = (p * n * 8.45) / 100;
          return (si);
       }
    }
Output:
                            Operator Overloading
          Def: Re-defining the functionality of an operator is nothing but ―Operator Overloading‖.
         With the support of operator overloading, you can use any of the existing operators with
           the combination of objects.
          For example to add two numbers, you write like this (a and b are the variables).
                    a+b
          But suppose you have two objects declared for ―Student‖ class. Then you can‘t write like
           this:
                    s1 + s2
          Finally, if you want to use the operator with the combination of objects, you require
           ―Operator Overloading‖.
          To implement this feature, write the ―Operator method‖ as follows:
using    System;
using    System.Collections.Generic;
using    System.Linq;
using    System.Text;
namespace OperatorOverloadingDemo
{
  class PersonHeight
  {
     //data members
     private int Feet, Inches;
         //methods
         public void SetHeight(int Feet, int Inches)
         {
            this.Feet = Feet;
            this.Inches = Inches;
         }
         //operator method
         public static PersonHeight operator - (PersonHeight p1, PersonHeight p2)
         {
            PersonHeight ph = new PersonHeight();
            if (p1.Inches < p2.Inches)
            {
                p1.Feet--;
                p1.Inches += 12;
            }
            ph.Inches = p1.Inches - p2.Inches;
            ph.Feet = p1.Feet - p2.Feet;
            return (ph);
         }
     }
Output:
Types of Generics:
      Generic Classes:
               The generic represents a data type, during the object‘s life time of the class.
      Generic Methods:
               The generic represents a data type, during the method execution.
    According to generic classes, when an instance is created, the required type of values
         could be stored as the data members.
    According to generic methods, when you call a method, you can pass different types of
         arguments to the same method, without overloading it.
          Object Construction:
                 classname<data type> objname = new classname<data type>;
          Method Calling:
                 methodname<data type>(value);
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
                                                                              Page 117 of 553
 namespace GenericClassesDemo
 {
   class Sample<T>
   {
      T n;
      public void Set(T n)
      {
         this.n = n;
      }
      public void Print()
      {
         Console.WriteLine(n);
      }
   }
   class Program
   {
      static void Main(string[] args)
      {
         Sample<int> s1 = new Sample<int>();
         s1.Set(10);
         s1.Print();
               Console.Read();
          }
      }
 }
Output:
     using    System;
     using    System.Collections.Generic;
     using    System.Linq;
     using    System.Text;
     namespace GenericMethodsDemo
     {
       class Sample
       {
          public void ReverseAndPrint<T>(T[] arr)
          {
    class Program
    {
       static void Main(string[] args)
       {
          int[] intArray = { 3, 5, 7, 9, 11 };
          string[] stringArray = { "first", "second", "third" };
          double[] doubleArray = { 3.567, 7.891, 2.345 };
             Console.Read();
        }
    }
}
Output:
                                         Properties
     ―Properties‖ are one of the new features of C#.
     It‘s taken from ―Visual Basic‖, not from C/C++.
     Generally, ―Properties‖ concept not used in the classes, in some rare cases and complex /
            large scale classes, those are used.
     In simple, properties are extensions to ―data members‖.
     As you know that a data member contains a value, a property implements additional
            logic on that data member, especially when its value is changed.
     For example, you imaging a windows form.
IMP Note: No memory gets allocated for the property. So that it can‘t store any value. To store
the actual value, we use a ―private data member‖.
Note: There should be some difference in the variable name and property name.
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace PropertyDemo
  {
    class Student
    {
       //private fields
       private string studentname_val;
       private int age_val;
          //public properties
          public string StudentName
          {
             set
             {
                if (value.Length <= 20)
                {
                    Console.WriteLine("The student name is changed as " + value);
                    studentname_val = value;
                }
                else
                {
                    Console.WriteLine("Why you are assigning two large name...?");
                }
             }
             get
             {
                return studentname_val;
             }
          }
                                                                                     Page 122 of 553
        public int Age
        {
          set
          {
              if (value>=18 && value<=60)
              {
                  Console.WriteLine("The student age is changed as " + value);
                  age_val = value;
              }
              else
              {
                  Console.WriteLine("Why you are assigning the wrong age...?");
              }
          }
          get
          {
              return age_val;
          }
        }
    }
    class Program
    {
       static void Main(string[] args)
       {
          Student stu = new Student();
            stu.StudentName = "Syam";
            Console.WriteLine(stu.StudentName);
            Console.WriteLine();
            stu.Age = 25;
            Console.WriteLine(stu.Age);
            Console.WriteLine();
            stu.StudentName = "abcdefghijklmnopqrstuvwxyz";
            Console.WriteLine(stu.StudentName);
            Console.WriteLine();
            stu.Age = 900;
            Console.WriteLine(stu.Age);
            Console.Read();
        }
    }
}
    Ex:
      private string name;
      public string Name
      {
               get
               {
                       return (name);
               }
      }
   Ex:
      private string name;
      public string Name
      {
               set
               {
                       name = value;
               }
      }
   Ex:
      public string Name { get; set; }
   All of the examples up to now have been implemented with one or more classes within
        the same file.
       But in the real programming world, each class will be implemented in individual file.
       To do so,
            o   Click on ―Project‖ menu – ―Add Class‖.
            o   Enter the name of the new class.
            o   Click on ―Add‖ button to confirm.
            o   Then a new file will be created in the same project named as:
                         classname.cs
                Note: (cs stands for C Sharp)
Demo.cs
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace ClassDefInSeperateFiles
{
  class Demo
  {
     public void DemoMethod()
     {
        Console.WriteLine("This is demo method...");
     }
  }
}
Program.cs
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
Output:
                                 Partial Classes
    The ―partial‖ keyword allows you to define a class, struct or interface across multiple
       files.
    As you learned above, each class will be placed in individual files.
    But in some situations in future, you may require to define a class within multiple files. In
       other words, the class definition can be split into multiple files.
    For example, if multiple programmers need to develop a class simultaneously, this may
       be required. In the same way, in windows applications, the automatic code generator
       generates some design part code for your own form class. In this case also, ―partial
       classes‖ are required.
Implementation:
                MyClassPart1.cs
                        partial class myclass
                        {
                                 //some members
                        }
SampleClassPart1.cs
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace PartialClasses
{
  partial class SampleClass
  {
    public void FirstMethod()
    {
        Console.WriteLine("This is first method.");
    }
  }
}
SampleClassPart2.cs
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace PartialClasses
{
  partial class SampleClass
  {
    public void SecondMethod()
    {
        Console.WriteLine("This is second method.");
    }
  }
}
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace PartialClasses
  {
    partial class SampleClass
    {
      public void ThirdMethod()
      {
          Console.WriteLine("This is third method.");
      }
    }
  }
Program.cs
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace PartialClasses
  {
    class Program
    {
       static void Main(string[] args)
       {
          SampleClass sc = new SampleClass();
          sc.FirstMethod();
          sc.SecondMethod();
          sc.ThirdMethod();
          Console.Read();
       }
    }
  }
Output:
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace IndexerDemo
{
  class IndexDemo
  {
     //array field
     public string[] countries = new string[10];
        //constructor
        public IndexDemo()
        {
           for (int i = 0; i < countries.Length; i++)
              countries[i] = "Not set";
        }
        //method
        public void ShowCountries()
        {
          //indexer
          public string this[int ind]
          {
             get
             {
                return countries[ind];
             }
             set
             {
                countries[ind] = value;
             }
          }
      }
      class Program
      {
         static void Main(string[] args)
         {
            IndexDemo id = new IndexDemo();
id.ShowCountries();
              Console.Read();
          }
      }
  }
Output:
1) Implementation Inheritance:
2) Interface Inheritance:
1) Single Inheritance
2) Hierarchical Inheritance
        An      inheritance    relationship,
                                                                   BaseClass
         with only one super class and
         multiple sub classes.
DerivedClass 1 DerivedClass 2
3) Multi-Level Inheritance
4) Multiple Inheritance
        An      inheritance     relationship,
         with only multiple super classes
                                                     BaseClass 1               BaseClass 2
         and only one sub class.
      ―Multiple               Implementation
         Inheritance‖ is not supported                          DerivedClass
         by C#, but ―Multiple Interface
         Inheritance‖ is supported by C#.
           An inheritance relationship
            that        contains         a
                                              Intermediate Class 1         Intermediate Class 2
            combination of any other
            two types of inheritances.
           Ex:                                                  DerivedClass
              Multiple +
                   Hierarchical Inheritance
              Multiple + Multi Level Inheritance etc.
Note: Other OOP languages like C++ support multiple inheritance. But C# and VB.NET doesn‘t
support multiple inheritance to avoid some practical problems while developing future GUI
applications like windows forms applications, web sites etc.
        But instead, C# and VB.NET supports ―multiple interface inheritance‖, because it doesn‘t
cause any practical problems.
   Invoke members
              obj.SuperClassMember
obj.SubClassMember
Example
 In the above example, we have two classes called ―A‖ and ―B‖. The inheritance
    relationship has been established between these classes. Now, the ―A‖ class is called as
    ―Super‖ class and ―B‖ class is called as ―Sub‖ class. All the members of ―A‖ class are
    exactly copied into ―B‖ class. Finally, whenever you construct an object for the ―B‖ class,
    you can access both ―Hello()‖ method and ―Hai()‖ method also from that object. This is
    what we learned up-to-now.
 But sometimes, some of the super class members may not be accessible directly from
    the sub class‘s object. This kind of nature depends on the ―access modifiers‖, we use in
    the super class, while we declare the super class members.
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace SimpleInheritanceDemo
  {
    //super class
    class Country
    {
       public void ShowCountry()
       {
          Console.WriteLine("This is India..");
       }
    }
      //sub class
      class State : Country
      {
         public void ShowState()
         {
            Console.WriteLine("This is Andhra Pradesh..");
         }
      }
      class Program
      {
         static void Main(string[] args)
         {
            //create instance for sub class
            State st = new State();
              Console.Read();
          }
      }
  }
Output:
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace ProtectedModifierDemo
 {
   //super class
   class Country
   {
      protected void ShowCountry()
      {
         Console.WriteLine("This is India..");
      }
   }
   //sub class
   class State : Country
   {
      public void ShowState()
      {
         ShowCountry();
         Console.WriteLine("This is Andhra Pradesh..");
      }
   }
   class Program
   {
      static void Main(string[] args)
      {
         //create instance for sub class
         State st = new State();
         //access the members
         st.ShowState();
         Console.Read();
      }
   }
Output:
        }
        class two : one //can‘t inherit this. Will give a compilation error.
        {
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace NewKeywordDemo
  {
    class US
    {
       public void ShowCountry()
       {
          Console.WriteLine("This is United States.");
       }
    }
    class India : US
    {
       public new void ShowCountry()
       {
          Console.WriteLine("This is India.");
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          India i = new India();
          i.ShowCountry();
          Console.Read();
       }
    }
  }
Output:
namespace VirtualDemo
{
  class US
  {
     public virtual void ShowCountry()
     {
        Console.WriteLine("This is United States.");
     }
  }
  class India : US
  {
     public override void ShowCountry()
     {
        Console.WriteLine("This is India.");
     }
  }
  class Program
  {
     static void Main(string[] args)
     {
        India i = new India();
        i.ShowCountry();
        Console.Read();
     }
  }
}
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace BaseKeywordDemo
 {
   class US
   {
      public virtual void ShowCountry()
      {
         Console.WriteLine("This is United States.");
      }
   }
   class India : US
   {
      public override void ShowCountry()
      {
         base.ShowCountry(); //call the base class method
         Console.WriteLine("This is India.");
      }
   }
   class Program
   {
Output:
Abstract Methods
      The abstract method is same as ―pure virtual functions‖ in C++.
      The abstract method can be declared with ―abstract‖ keyword like this:
               public abstract void samplemethod();
      The abstract method doesn‘t contain method definition; it contains only method
       declaration as above.
      The abstract methods can be declared only within abstract classes.
Abstract Classes
      A class that is declared with ―abstract‖ keyword is called as ―abstract class‖.
               abstract class classname
               {
    Rule: If a class contains at least one abstract method, that class should be declared as
       abstract class.
    The abstract class can contain abstract methods, non-abstract class and normal data
       members also.
      Note: You can‘t create an object for the abstract class. It can be inherited from another
       non-abstract class.
    The non-abstract class, that inherits the abstract class, should implement the
       definition(s) (with ―override‖ keyword) for all of the abstract methods declared in the
       abstract class.
    Note: The access modifiers used in the base and derived classes for the abstract
       methods should be same.
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace AbstractDemo
{
  //abstract class
  abstract class MyBaseClass
  {
     public abstract void FirstMethod();
     public void SecondMethod()
     {
        Console.WriteLine("This is Non-Abstract Method");
     }
  }
  //non-abstract class
  class MyDerivedClass : MyBaseClass
  {
Output:
                                   Summary of Modifiers
       Up to now, you learned several modifiers like static, new, virtual, abstract, override,
            sealed.
           You get a summary of all of these modifiers with following table:
Sl.
             Modifier      Applies to                              Description
No
                                            The method hides a base class method with same
 1          new          Methods only
                                            signature.
                                            The member does not depends / instantiates with any of
 2          static       All members        with its class‘s objects. It can be accessed with its class
                                            name.
 3          virtual      Methods only       The member can be overridden by a derived class.
                                            The abstract class can‘t be instantiated.
                                            The abstract method is nothing but a virtual method that
                         Classes    and
 4          abstract                        contains only declaration with no definition. It should be
                         Methods only
                                            implemented with ―override‖ keyword in the derived
                                            class.
                                            The member overrides an inherited virtual or abstract
 5          override     Methods only
                                            member of the base class.
    Features of Interfaces:
            o   The interface can be declared with ―interface‖ keyword, as follows:
                         interface interfacename
                         {
                         }
            o   The interface contains only method declarations and can‘t contain method
                definitions (similar to the abstract methods).
            o   The interface can‘t contain any data members but can contain ―automatic
                properties‖ (Already you know that the automatic property doesn‘t contain
                definitions for ―get‖ and ―set‖ accessors).
            o   Interface methods are by default ―public‖. You can‘t use another access modifier
                like private and public etc.
            o   The interface can‘t be instantiated. That means you can‘t create an object for the
                interface.
            o   The interface can‘t contain constructors.
            o   The class that inherits the interface is called as Implementation Class.
            o   The implementation class should implement the definitions for all the interface
                methods. If not, it would generate compile time errors.
            o   One interface can be inherited by any no. of classes (Hierarchical inheritance).
            o   One class can inherit any no. of interfaces (Multiple inheritance).
            o   The interface methods can‘t be declared as ―virtual‖ or ―static‖ in the interface
                definition.
  namespace InterfaceDemo
  {
    interface SimpleInterest
    {
       double GetSimpleInterest(double P, int N, double R);
    }
    class SimpleInterestImpl : SimpleInterest
    {
       public double GetSimpleInterest(double P, int N, double R)
       {
          return ((P * N * R) / 100);
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          SimpleInterestImpl sii = new SimpleInterestImpl();
          Console.WriteLine("Simple Interest: " + sii.GetSimpleInterest(5000, 3, 4.5));
          Console.Read();
       }
    }
  }
                                        Structures
         This concept is not new in C#; it is taken from C language.
       In C language‘s structures, you can write only some member variables, called as ―data
          members‖ / ―fields‖. But in C#‘s structures, you can write fields along with some
          methods also.
         So, In C#, structures are almost all similar to the classes, but having some differences
          with the classes.
Implementation:
         Define structure
                  struct structurename
                  {
                          //fields
                          //methods
                  }
 namespace StructuresDemo
 {
   struct Employee
   {
      //fields
      private int EmployeeID;
      private string EmployeeName;
      private double Salary, Tax, NetSalary;
       //methods
       public void ReadData()
       {
          Console.Write("Enter Employee ID: ");
          EmployeeID = Convert.ToInt32(Console.ReadLine());
          Console.Write("Enter Employee Name: ");
          EmployeeName = Console.ReadLine();
          Console.Write("Enter Salary: ");
          Salary = Convert.ToDouble(Console.ReadLine());
       }
       public void Calculate()
       {
          Tax = Salary * 10 / 100;
          NetSalary = Salary - Tax;
       }
       public void DisplayData()
       {
          Console.WriteLine("\n\nEmployee ID: " + EmployeeID);
          Console.WriteLine("Employee Name: " + EmployeeName);
          Console.WriteLine("Salary: " + Salary);
          Console.WriteLine("Tax: " + Tax);
          Console.WriteLine("Net Salary: " + NetSalary);
       }
     }
     class Program
     {
        static void Main(string[] args)
        {
           //create structure instance
           Employee e = new Employee();
           //call the methods
           e.ReadData();
           e.Calculate();
           e.DisplayData();
           Console.Read();
        }
     }
 }
Implementation:
      When you want to implement this concept practically, simply take a new static class first.
      In this static class, write a static method, with the required name.
      In that method, the first argument should be like this:
                 this classname argumentname
      Here, in place of ―classname‖, specify the class name, for which you want to write the
       extension method.
      Then the ―argument name‖ acts as ―this‖ pointer in the code.
    Note: Even though it is defined as a ―static method‖ it is accessible as a non-static
       method from the object of the source class.
      Syntax:
       public static return_type method_name(this class_name arg, <other args if any>)
       {
                 //some code
       }
      Limitation: You can‘t add a ―static method‖ for an existing class.
StringExtension.cs
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace ExtensionMethodsDemo
  {
    static class StringExtension
    {
       public static string Reverse(this String str)
       {
           char[] ch = str.ToCharArray();
           Array.Reverse(ch);
           string mystr = new String(ch);
           return (mystr);
       }
    }
  }
Program.cs
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace ExtensionMethodsDemo
  {
    class Program
    {
       static void Main(string[] args)
       {
          string s = "abcdefghijklmnopqrstuvwxyz";
          Console.WriteLine(s.Reverse());
          Console.Read();
       }
    }
  }
Output:
Implementation Syntax:
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
              Console.Read();
          }
      }
  }
Output:
  namespace MultiCastDelegatesDemo
  {
    class Test
    {
       public void ShowSquare(int n)
       {
          int x = n * n;
          Console.WriteLine("Square: " + x);
       }
       public void ShowCube(int n)
       {
          int x = n * n * n;
          Console.WriteLine("Cube: " + x);
       }
    }
    class Program
    {
       delegate void MyDelegate(int n);
       static void Main(string[] args)
       {
          Test t = new Test();
          MyDelegate md = new MyDelegate(t.ShowSquare);
          md += new MyDelegate(t.ShowCube);
          md.Invoke(10);
          Console.Read();
       }
    }
  }
Output:
                               Manipulations on Arrays
        Copying arrays:
                 Syn: arrayname.CopyTo(DestinationArray, StartIndex);
                 Ex: a.CopyTo(b, 0);
                 Note: The size and dimensions of both a and b arrays, should be same. It copies
                 all the elements into the destination array.
        Sorting arrays:
                 Syn: Array.Sort(arrayname);
                 Ex: Array.Sort(a);
                 Note: ―Sort‖ is a static method of ―Array‖ class. It sorts all the array elements in
                 ascending order.
        Reversing arrays:
                 Syn: Array.Reverse(arrayname);
                 Ex: Array.Reverse(a);
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace ArrayClassDemo
 {
   class Program
   {
      static void Main(string[] args)
      {
         //single dimensional array
         Console.WriteLine("Single dimensional array:");
         int[] a = { 643, 32948, 39, 23094, 112};
         foreach (int i in a)
             Console.Write(i + " ");
         Console.WriteLine("\nLength: " + a.Length);
         Console.WriteLine("Rank: " + a.Rank);
           //string array
           Console.WriteLine("\nString array:");
              //copying arrays
              Console.WriteLine("\n\nSingle dim array after copy:");
              int[] c = new int[5];
              a.CopyTo(c, 0);
              foreach (int i in c)
                 Console.Write(i + " ");
              //sorting arrays
              Array.Sort(c);
              Array.Sort(s);
              Console.WriteLine("\n\nSingle dim array after sorting:");
              foreach (int i in c)
                 Console.Write(i + " ");
              Console.WriteLine("\n\nString array after sorting:");
              foreach (string i in s)
                 Console.Write(i + " ");
              //reversing arrays
              Array.Reverse(c);
              Array.Reverse(s);
              Console.WriteLine("\n\nSingle dim array after reversing:");
              foreach (int i in c)
                 Console.Write(i + " ");
              Console.WriteLine("\n\nString array after reversing:");
              foreach (string i in s)
                 Console.Write(i + " ");
              Console.WriteLine("\n");
           //searching an element
           Console.WriteLine("Index of 'Java' in the string array is : " + Array.IndexOf(s,
  "Java"));
              Console.Read();
          }
      }
  }
  namespace MathClassDemo
  {
    class Program
    {
       static void Main(string[] args)
       {
          Console.WriteLine(Math.Abs(-84));
          Console.WriteLine(Math.Pow(10, 3));
          Console.WriteLine(Math.Min(5, 100));
          Console.WriteLine(Math.Max(5, 100));
          Console.WriteLine(Math.Min(25, Math.Min(78, 87)));
          Console.WriteLine(Math.Max(25, Math.Max(78, 87)));
          Console.WriteLine(Math.Sqrt(9));
          Console.WriteLine(Math.Floor(10.56));
          Console.WriteLine(Math.Ceiling(10.56));
          Console.WriteLine(Math.Round(10.56));
          Console.WriteLine(Math.Round(10.23));
          Console.WriteLine(Math.Round(10.2342, 2));
          Console.WriteLine(Math.Round(10.2392, 2));
          Console.WriteLine(Math.Sign(10));
          Console.WriteLine(Math.Sign(-10));
          Console.WriteLine(Math.PI);
          Console.Read();
       }
    }
  }
using   System;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;
namespace StringDemo
{
  class Program
  {
     static void Main(string[] args)
     {
        //create string object
        string s = "I am a .NET Developer";
        Console.WriteLine("The original string is: " + s);
        Console.WriteLine("The original string's length is: " + s.Length);
          //copy strings
          string s1;
          s1 = s;
          Console.WriteLine("\nThe copied string is: " + s1);
          //concatenate strings
          string s2 = "I am working in Wipro.";
          string s3;
          s3 = s1 +". " + s2;
          Console.WriteLine("\nThe concatenated string is: " + s3);
          //compare strings
          if (s1 == s2)
              Console.WriteLine("\ns1   and s2 are equal");
          else
              Console.WriteLine("\ns1   and s2 are not equal");
          string s4 = s1;
          if (s1 == s4)
              Console.WriteLine("\ns1   and s4 are equal");
          else
              Console.WriteLine("\ns1   and s4 are not equal");
            //right padding
            string s19 = s.PadRight(26, '*');
            Console.WriteLine("\nString after right padding: " + s19);
            Console.Read();
        }
    }
}
Object Implementation:
        Create an instance for “System.DateTime” structure:
                 DateTime dtobj;
        Assign any date&time value:
                 dtobj = Convert.ToDateTime(―mm/dd/yyyy hh:mi:ss AM/PM‖);
        Assign System date&tme:
                 dtobj = DateTime.Now;
Date Comparisons
        Date comparisons are very simple in C#, because ―DateTime‖ structure overloads the
         necessary relational operators such as ―==‖, ―!=‖, ―<‖, ―>‖, ―<=‖, ―>=‖.
        You can directly use these operators between two dates and get the appropriate result.
Date Difference
        To find out the difference between two dates, simply use ―-― operator, which is already
         overloaded.
        When you use this, you can get the result as an ―System.TimeSpan‖ object.
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 namespace DateTimeDemo
 {
   class Program
   {
      static void Main(string[] args)
      {
         //create DateTime obj
         DateTime dt1;
         dt1 = Convert.ToDateTime("7/16/2009 6:23 PM");
         DateTime dt2 = DateTime.Now;
         //display dates
         Console.WriteLine("dt1 is: " + dt1.ToString());
         Console.WriteLine("dt2 is: " + dt2.ToString());
        //adding values
        DateTime dt3 = dt2.AddDays(5);
        Console.WriteLine("\ndt2 after adding   5 days: " + dt3.ToShortDateString());
        DateTime dt4 = dt2.AddMonths(5);
        Console.WriteLine("\ndt2 after adding   5 months: " + dt4.ToShortDateString());
        DateTime dt5 = dt2.AddYears(5);
        Console.WriteLine("\ndt2 after adding   5 years: " + dt5.ToShortDateString());
        DateTime dt6 = dt2.AddHours(5);
        Console.WriteLine("\ndt2 after adding   5 hours: " + dt6.ToLongTimeString());
        DateTime dt7 = dt2.AddMinutes(5);
        Console.WriteLine("\ndt2 after adding   5 minutes: " + dt7.ToLongTimeString());
        DateTime dt8 = dt2.AddSeconds(5);
        Console.WriteLine("\ndt2 after adding   5 seconds: " + dt8.ToLongTimeString());
        //date comparision
        if (dt1 == dt2)
            Console.WriteLine("\ndt1 and dt2 are equal.");
        else if (dt1 > dt2)
            Console.WriteLine("\ndt1 is greater than dt2.");
        else if (dt1 < dt2)
            Console.WriteLine("\ndt1 is less than dt2.");
Output:
Implementation:
      Create an instance:
                 Random r = new Random();
      Generate the random number based on the given boundary values:
                 r.Next(min value, max value);
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  namespace RandomDemo
  {
    class Program
    {
       static void Main(string[] args)
       {
          Random r = new Random();
          for (int i = 0; i < 300; i++)
          {
              Console.Write(r.Next(1, 300) + ", ");
          }
          Console.Read();
       }
    }
  }
                                    Collections
      The concept of ―collections‖ is basically developed from ―Arrays‖.
      Already you know that, arrays are multiple value containers of fixed type.
      In order to hold different types of values on the same array, you require collections.
    Another advantage of collections is those are dynamic sizable. In other words, the array
       is of fixed size and the collection is of dynamic size.
    Finally, if you don‘t know how many values are to be stored in the array at the time of its
       declaration, you require to use ―collections‖; (or) if you want to store different type of
       values in the same array, at that case also, you require to use ―collections‖.
      .NET offers some pre-defined classes for maintenance of collections.
Collection Classes:
      List:
               1) Contains n no. of values of same type. It‘s a generic class.
               2) This is member of ―System.Collections.Generic” namespace.
      ArrayList:
               1) Contains n no. of values of different types.
     Import namespace:
              using System.Collections.Generic;
     Create instance:
              List<data type> obj = new List<data type>();
     Add values:
              obj.Add(value);
     Get the currently existing no. of values in the collection:
              obj.Count
     Get the individual element in the collection:
              obj[index];
     Import namespace:
              using System.Collections;
     Create instance:
              ArrayList obj = new ArrayList();
     Add values:
              obj.Add(value);
     Get the currently existing no. of values in the collection:
              obj.Count
     Get the individual element in the collection:
              obj[index];
using System.Collections.Generic;
 namespace ListClass
 {
   class Program
              MyMessages.Add("Good Morning");
              MyMessages.Add("Good Afternoon");
              MyMessages.Add("Good Evening");
              MyMessages.Add("Good Night");
//MyMessages.Add(10); //error
              Console.Read();
          }
      }
  }
Output:
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  using   System.Collections;
  namespace ArrayListClass
  {
    class Program
    {
       static void Main(string[] args)
       {
          ArrayList al = new ArrayList();
             Console.Read();
         }
     }
 }
Output:
                           Collection Initializer
      As per the previous examples with collections, we require to add the values to the
         collections using ―Add()‖ method.
        Suppose you want to add so many elements to the collection. Then if you are using it
         takes ―Add()‖ method (as above), it takes no. of lines of code.
        To solve this problem, ―Collection Initializer‖ can be used.
        Purpose: To initialize the elements of a collection, at the time declaration.
        Syntax:
                  1) “List” collection class:
                          List<data type> obj = new List<data type>() { val1, val2, …. };
                  2) “ArrayList” collection class:
                          ArrayList obj = new ArayList() { val1, val2, …. };
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  using   System.Collections;
  namespace CollectionInitializerDemo
  {
      class Program
      {
          static void Main(string[] args)
          {
             //Collection Initializer with List class
             Console.WriteLine("List:");
             List<string> lst = new List<string>() { "one", "two", "three", "four" }; //collection
  initializer
             lst.Add("five"); //add additional elements if required
            Console.WriteLine("\n\nArray List:");
            ArrayList arrlst = new ArrayList() { "emp_001", "Srinivas", 8900, "Washington" };
  //collection initializer
            arrlst.Add(DateTime.Now); //add additional elements if required
            foreach (object s in arrlst)
               Console.WriteLine(s);
              Console.Read();
          }
      }
  }
Output:
Note: By default, ―System.Drawing‖ assembly will not be linked with the ―Console applications‖.
That‘s why you need to add a reference to that as follows:
             Click on ―Project‖ menu – ―Add Reference‖.
             Select ―System.Drawing‖ assembly.
             Click on OK. Then the ―System.Drawing‖ assembly will be linked with the current
              project and it will be displayed in ―References‖ folder in the Solution Explorer.
Implementation:
         Import the namespace:
                  using System.Drawing.Printing;
         Construct the object:
                  PrintDocument obj = new PrintDocument();
         Assign the document name, that is to be printed:
                  obj.DocumentName = ―file path to be printed‖;
         Start Printing:
                  obj.Print();
  using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Text;
  using   System.Drawing.Printing;
  namespace PrintingDemo
  {
    class Program
    {
Output:
Library: System.IO.DriveInfo
The ―DriveInfo‖ class object can represent a drive on the computer. It offers several properties
and methods to access the related information of the drive.
Object Construction:
            Syn: DriveInfo obj = new DriveInfo(―drive letter‖);
            Ex: DriveInfo obj = new DriveInfo(―c‖);
You can observe the list of all available properties, methods of this class.
    using   System;
    using   System.Collections.Generic;
    using    System.Linq;
    using   System.Text;
    using   System.IO;
                                                                                         Page 184 of 553
  namespace DriveInfoDemo
  {
    class Program
    {
       static void Main(string[] args)
       {
          Console.WriteLine("Enter the drive letter (a to z):");
          string driveletter = Console.ReadLine();
              if (d.IsReady)
              {
                  Console.WriteLine(d.Name);
                  Console.WriteLine(d.DriveType);
                  Console.WriteLine(d.VolumeLabel);
                  Console.WriteLine(d.DriveFormat);
                  Console.WriteLine(d.TotalSize + " bytes.");
                  Console.WriteLine(d.TotalFreeSpace + " bytes.");
              }
              else
                  Console.WriteLine(d.Name + " - " + " Not Ready.");
              Console.Read();
          }
      }
  }
Output:
 using    System;
 using    System.Collections.Generic;
 using    System.Linq;
 using    System.Text;
 using    System.IO;
 namespace GetDrivesDemo
 {
                                                                       Page 185 of 553
      class Program
      {
         static void Main(string[] args)
         {
            DriveInfo[] dinfo = DriveInfo.GetDrives();
            Console.WriteLine(dinfo.Length + " drives found on this computer.");
            foreach (DriveInfo d in dinfo)
            {
                Console.WriteLine();
                if (d.IsReady)
                {
                    Console.WriteLine(d.Name);
                    Console.WriteLine(d.DriveType);
                    Console.WriteLine(d.VolumeLabel);
                    Console.WriteLine(d.DriveFormat);
                    Console.WriteLine(d.TotalSize + " bytes.");
                    Console.WriteLine(d.TotalFreeSpace + " bytes.");
                }
                else
                    Console.WriteLine(d.Name + " - " + d.DriveType + " - Not Ready.");
            }
            Console.Read();
         }
      }
  }
Output:
Library: System.IO.DirectoryInfo
         This class object represents a folder on the file system. This able to get the information
of the folder and also to perform certain operations on that folder.
Object Construction:
         Syn: DirectoryInfo obj = new DirectoryInfo(―path of the directory‖);
         Ex: DirectoryInfo obj = new DirectoryInfo(―c:\\windows‖);
You can observe the list of all available properties, methods of this class.
using System.IO;
   namespace DirectoryInfoDemo1
   {
     class Program
     {
        static void Main(string[] args)
        {
           string directorypath = "c:\\windows\\help";
           DirectoryInfo dinfo = new DirectoryInfo(directorypath);
               if (dinfo.Exists)
               {
                   Console.WriteLine("Directory Name: " + dinfo.Name);
                   Console.WriteLine("Directory Full Path: " + dinfo.FullName);
                   Console.WriteLine("\nCreated on: " + dinfo.CreationTime);
                   Console.WriteLine("Last accessed on: " + dinfo.LastAccessTime);
                   Console.WriteLine("Last modified on: " + dinfo.LastWriteTime);
                   Console.WriteLine("\nParent: " + dinfo.Parent.FullName);
                   Console.WriteLine("Root: " + dinfo.Root);
                 Console.WriteLine("\nFiles:");
                 FileInfo[] fobjs = dinfo.GetFiles();
                 foreach (FileInfo f in fobjs)
                    Console.WriteLine(f.FullName);
                 Console.WriteLine("\nSub Directories:");
                 DirectoryInfo[] dobjs = dinfo.GetDirectories();
                 foreach (DirectoryInfo d in dobjs)
                    Console.WriteLine(d.FullName);
               }
               else
                  Console.WriteLine(directorypath + " is not available on the system.");
               Console.Read();
           }
       }
   }
  using   System;
  using   System.Collections.Generic;
  using    System.Linq;
  using   System.Text;
  using   System.IO;
  namespace DirectoryInfoDemo2
  {
    class Program
    {
       static void Main(string[] args)
       {
          Console.WriteLine("Enter the directory path:");
          string directorypath = Console.ReadLine();
          DirectoryInfo dinfo = new DirectoryInfo(directorypath);
              if (!dinfo.Exists)
              {
                  dinfo.Create();
                  Console.WriteLine("Directory created.");
              }
              else
                  Console.WriteLine(directorypath + " is already exists.");
              Console.Read();
          }
      }
  }
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 using   System.IO;
 namespace DirectoryInfoDemo3
 {
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Enter the directory path:");
         string directorypath = Console.ReadLine();
         DirectoryInfo dinfo = new DirectoryInfo(directorypath);
             if (dinfo.Exists)
             {
                 dinfo.Delete(true);
                 Console.WriteLine("Directory deleted.");
             }
             else
                 Console.WriteLine(directorypath + " doesn't exists.");
             Console.Read();
         }
     }
 }
Output:
Library: System.IO.FileInfo
         This class object represents a file on the file system. This able to get the information of
the file and also to perform certain operations on that folder.
Object Construction:
         Syn: FileInfo obj = new FileInfo(―path of the file‖);
         Ex: FileInfo obj = new FileInfo(―c:\\tc\list.h‖);
You can observe the list of all available properties, methods of this class.
 using   System;
 using   System.Collections.Generic;
 using   System.Linq;
 using   System.Text;
 using   System.IO;
 namespace FileInfoDemo
 {
   class Program
   {
      static void Main(string[] args)
      {
         string filepath;
         Console.WriteLine("Enter the file path:");
         filepath = Console.ReadLine();
             if (fobj.Exists)
             {
                 Console.WriteLine("\nName: " + fobj.Name);
                 Console.WriteLine("Full Name: " + fobj.FullName);
                 Console.WriteLine("Extension: " + fobj.Extension);
                 Console.WriteLine("Directory: " + fobj.DirectoryName);
                 Console.WriteLine("File Size: " + fobj.Length + " bytes");
                 Console.WriteLine("Created on: " + fobj.CreationTime);
                 Console.WriteLine("Last Accessed on: " + fobj.LastAccessTime);
                 Console.WriteLine("Last Modified on: " + fobj.LastWriteTime);
             }
             else
                 Console.WriteLine("File not found.");
             Console.Read();
         }
     }
 }
                                    File Streams
      To write / read the content to / write the file, you require file streams.
      A file stream acts as a pointer for the file, which contains the memory address of the file
        on the disc.
      There are two types of file streams.
                1) Reading Streams
                2) Writing Streams