OPPS Concept

·

62 min read

Constructor Overloading

Constructor overloading is a same name a constructor name but default parameter its called constructor overloading

hello

Static Constructor:-

  1. A static Constructor is used to initialize static variables of the class and to perform a particular only once.

  2. Static Constructor is called only once, no metter how many object you create.

  3. Static Constructor is called before instance (default or parameterized)constructors.

  4. A static Constructor dose not take any parameters and dose not use any access modifiers.

KEY POINTS OF STATIC CONSTRUCTOR:

-> Only one static constructor can be created the class.

-> It is called automaticcally before the first instance of the class created.

-> We cannot call static constructor directly.

→ A static constructor cannot be called explicitly. It is called automatically by the CLR (Common Language Runtime) when necessary, such as when accessing static members or creating an instance of the class.

Copy Constructor:-

It is use to copy the data from an existing object into a new object

or

The Constructor which creates an object by copying values from another object is called a copy constructor . The purpose of a copy constructor is to initilize a new instance to the value of an existing instance.

In c#, CopyConstructor which constains a parameter of same class type. The copy constructor in c# is useful whenever we want to initialize a new instance to the value of an exsting instance.

Private Constructor:-

When a constructor is created with a private specifier, it is not possible for other classes to drive from this class, neither is posiable to create an instance of this class. They are usally used in classes that contain static member only. Some key points of a private constructor are:

One use of a private constructor is when we have only static member.

Once we provide a constructor that is private or public or any, the compailer will not add parameter-less public constructor to the class.

In the presence of parameterless private constructor you cannot create a default constructor.

We can have parameters in parameter constructor

Static Class:-

Classses that cannot be instanitiated or inherited (instanitiated meens we are not create a method in static class) or(inherited meens we not inherited also ) are know as static classes and the static keyword is used before that class name that consists of static data members and static method.

It is not possible to create an instance of static class using the new keyword. The main features of static class are as follows :

  1. they can only contain static members.

  2. They cannot be instantiated or inherited and cannot contain instance constructors. However, the developer can create static constructors to initialize the static members.

using System;

namespace Pratic3
{
    static class Product  // here i am use static keyword that  by it is a static class  
    {
        public static int productId;
        public static string productName;   // these are all variable is static 
        public static int productPrice;

        static Product()   // static constructor
        {
            productId = 111;
            productName = "Guitar";
            productPrice = 5000;
        }
        public static void getproductDitails() //static Method                                            //in static class all is static we create non static it will show error
        {
            Console.WriteLine("product id = {0}",productId);     
            Console.WriteLine("Product Name={0}",productName);
            Console.WriteLine("Product Price {0}",productPrice);
        }
        public static void getDiscount()
        {
            int d_amount = productPrice / 10;
            Console.WriteLine("Your discount ammount is {0}",d_amount);
            Console.WriteLine("Total cost of product is {0} ",(productPrice - d_amount));
        }
    }


   /* class Item : Product      // we can not inherit static class it will showing error
    {
        public void Access()
        {
            Console.WriteLine("Hello");
        }
    } */
    internal class StaticEX
    {
        static void Main()
        {
            Product.getproductDitails();
            Product.getDiscount();

          //  product p = new product();   // we can not create a object in static class it will givin error
        }

    }
}

DESTRUCTOR IN C# PROGRAM:-

A destructor is a spacieal method which has same name as the class but starts with the character ~ befor the class name and immediately de- allocates memory of object that are no longer required.

  • Destructor cannot be overloded or inherited.

  • Destructor cannot be explicitly invoked.

  • Destructor cannot specify access modifier and cannot take parameters.

using System;


namespace Pratic3
{
    class Person
    {
       public string name;      //if you not using access modifier so it by defaul private                                //
        public int  age;       // under the class all variable is private if you not use any access modifier
                                 //these variable is also called instance variable
        public Person(string name,int age)
        {
           this.name = name;
          this.age = age;
        }

        public string getName()            //get method
        {
            return this.name;
        }
        public int getAge()
        {
            return this.age;
        }

        ~Person()
        {
            Console.WriteLine("Destructor has been invoked !!....");
        }
    }


    internal class Destroctor
    {
        static void Main()
        {
            Person p = new Person("Sumit",21); //here pass the value

            Person p2 = new Person("Rahul", 23);

            Console.WriteLine(p.getName());
            Console.WriteLine(p.getAge());

            Console.WriteLine(".................");
            Console.WriteLine(p2.getName());
            Console.WriteLine(p2.getAge());


        }
    }
}

//Output
/*Sumit
21
.................
Rahul
23
Destructor has been invoked !!....     // destructor call two time it mens your program have two object 
Destructor has been invoked !!....*/

Destructor main work is one time your program will done then destructor will we run and clear the memory

Pass by value & pass by Reference Ref&out Keyword: (int manaly use method)

Pass by value

   //PassBy Value
using System;


namespace Pratic3
{
    internal class PassByValue
    {
        public void Pyv(int a)
        {
            a += 10;
            Console.WriteLine(a);
        }
        static void Main()
        {
            int value = 5;
            PassByValue P = new PassByValue();
            P.Pyv(value);   // here change value ans=15
            Console.WriteLine("------------------");
            Console.WriteLine(value);  //here not change value   //ans 5
            Console.ReadLine();
        }
    }
}

PassByRef (if you use passByRef then Boath are value is change

)

   //PassBy Ref
using System;


namespace Pratic3
{
    internal class PassByValue
    {
        public void PassByRef( ref int a) // ref key word is manatery
        {
            a += 10;
            Console.WriteLine(a);
        }
        static void Main()
        {
            int value = 5;   //value initilize
            PassByValue P = new PassByValue();
            P.PassByRef(ref value);   // here change value ans=15
            Console.WriteLine("------------------");
            Console.WriteLine(value);  //here also change value   //ans 15
            Console.ReadLine();
        }
    }
}

PassByOut

   //PassByOut
using System;


namespace Pratic3
{
    internal class PassByValue
    {
        public void PassByOut( out int a) // Out key word is manatery
        {
            a = 20;                // here initilize value   this is a main point here we pass the value but  PassByref we not pass value
            Console.WriteLine(a);
        }
        static void Main()
        {
            int value;    // here i am not pass any value 
            PassByValue P = new PassByValue();
            P.PassByOut(out value);   // here change value ans=20
            Console.WriteLine("------------------");
            Console.WriteLine(value);  //here also change value   //ans 20
            Console.ReadLine();
        }
    }
}
/*Out put
 20
------------------
20
*/

PASS BY REFFERENCE(memory address is call reffrence) (REF KEYWORD)

->The ref keyword causes arguments to be passed in a method by reference.

-> In call by reference,the called method changes the value of parameters passed to it form the calling method.

->Any changes made to the parameter to the parameters in the called method will be reflected in the parameter passed form the calling method when control passes back to the calling method.

-> it is nacessary that both the called method and the calling method must explicitly specify the ref keyword before the required parameters.

The variables passed by reference form the calling method must be first initialized.

Out KeyWord

The out keyword is similar to the ref keyword and causes arguments to be passed by reference (means send the ref not a value then change boath are value)

The only difference between two is that out keyword dose not require the variables that are passed by reference to be initialized

Both the called method and the calling method must explicitly use the out keyword

INHERITANCE IN C# PROGRAMMING

Inheritance :- getting the property execisting class to new class it called inheritance

  1. Inheritance provide reusability by allowing us to extended an existing class.

  2. The reasson behind oop programming is to promote the reusabilty of code and to reduce complexity in code it is possible by using inheritance

The Inheritance concept is based on a base class and drive class. Let us see the definition of a base and drive class.

-> BASE CLASS-is the class from which features are to be inherited into another class.

->Derived Class- it is class in which the base class feature are inherited.

Type of Inheritance

1 Single Inheritance

2 Multilevel inheritance

3 Hierarchical Inheritance

4 Hybrid Inheritance (it not saport c#)

5 Multiple Inheritance (we can access only interface)

       // this example a multiple inheritance 

using System;

namespace Practic3
{
    class Employee   // base class parent class supper class 
    {
        public int EmpId;
        public string EmpName;
        public int EmpAge;
        public int EmpContactNo;

        public void show()
        {
            Console.WriteLine("This is a method of base class");
        }
    }
    class PermanentEmployee:Employee  // here inherited parents class to child class
        public int permanentSalary;
        public int permanentHours;
    }
    class VisitingEmployee: Employee   // here inherited parents class to child class
    {
        public int VisitingSalary;
        public int VisitingHours;
    }
    internal class InheritanceEX
    {
        static void Main()
        {
            PermanentEmployee p = new PermanentEmployee();
            p.EmpId = 101; // here we write only p. all property are showingparent class and childe class aloso

            p.show();

            VisitingEmployee V=new VisitingEmployee();
            V.EmpId = 102;                     // here we write only V. all property are showingparent class and childe class aloso

            Console.WriteLine(p.EmpId);
            Console.WriteLine(V.EmpId);
        }
    }
}

Single Inheritance:-

Getting the property one pairant class to one childe class it call single inheritance (meens single inheritance one pairent and one childe class)

It is the type of inheritance in which there is one base class and one derived class

// Single inheritance example

using System;

namespace Pratic3
{
    class Employee   // One Parents class 
    {
        public int EmpId;
        public string EmpName;
        public int EmpAge;
        public int EmpContactNo;

        public void show()
        {
            Console.WriteLine("This is a method of base class");
        }
    }
    class PermanentEmployee:Employee  // One child class
    {
        public int permanentSalary;
        public int permanentHours;
    }

    internal class InheritanceEX
    {
        static void Main()
        {
            PermanentEmployee p = new PermanentEmployee();
            p.EmpId = 101;
            p.show();

            Console.WriteLine(p.EmpId);  
        }  
    }
}

Example 2

using System;

namespace Practic3
{
    class Welcome  // base class parent class 
    {
      public void Show1()
        {
            Console.WriteLine("This is a method of base class");
        }
    }
   class Hello:Welcome    // derived class childe class
    {
        public void Show2()
        {
            Console.WriteLine("This is a childe class method");
        }
    }
    internal class SimpleInheritance
    {
        static void Main()
        {
         Hello he = new Hello();
            he.Show1();
            he.Show2();

        }
    }
}

Hierarchial Inheritance:-

This is type of inheritance in which there are multiple classes derived from one base class.

This type of inheritance is used when there is a requirment of one class feature that is need in multiple classes.

using System;

namespace Pratic3
{
    class Welcome  // base class parent class 
    {
      public void Show1()
        {
            Console.WriteLine("This is a method of base class");
        }
    }
   class Hello1:Welcome  // inharit 1 drived class
    {
        public void Show2()
        {
            Console.WriteLine("This is a Method of 1 drived class ");
        }
    }
    class hello2:Welcome    // inharit 2 drived class
    {
      public void Show3()
        {
            Console.WriteLine("this is a method 2 drived class");
        }
    }
    internal class SimpleInheritance
    {
        static void Main()
        {

            Hello1 H1 = new Hello1();  // First drived class object
            H1.Show1 ();  // base class method call
            H1.Show2();   // 1 drived class method call

            Console.WriteLine("=============================");

            hello2 H = new hello2();  // 2 drived class object
            H.Show1();   // Base class method
            H.Show3();    // 2 drived class method


        }
    }
}

Multilevel Inheritance:-

One Class is Inharited to another class (derived class) Then the derived class agen become parent to anothe class is called multi level inheritance.

or

When one class is derived from anothe derived class then this type of inheritance is called multilevel inharitance

using System;

namespace Pratic3
{
    class Welcome  // base class parent class 
    {
      public void Show1()
        {
            Console.WriteLine("This is a method of base class");
        }
    }
   class Hello1:Welcome  //welcome is parent class 
    {
        public void Show2()
        {
            Console.WriteLine("This is a Method of 1 drived class ");
        }
    }
    class hello2:Hello1  // this time Hello1 is parent class to hello2 class
    {
      public void Show3()
        {
            Console.WriteLine("this is a method 2 drived class");
        }
    }
    internal class SimpleInheritance
    {
        static void Main()
        {

           Hello1 H1=new Hello1();  // Hello1 object only access show1 and show  because welcome class inherited to Hello1 class 
            H1.Show1 ();
            H1.Show2();

        //    H1.Equals show3()   if we write show3 it will showing error we can not access show3() method 

            Console.WriteLine("===========================");
            hello2 H2=new hello2 ();  // here we access all class method show1,show2,show3 
            H2.Show1 ();
            H2.Show2 ();
            H2.Show3 ();

        }
    }
}

MULTIPLE INHERITANCE:-

Multiple inheritance is a feature in which a class can inherit characteristics and features form more then one parent class

More then one parent inherit one child class is called multiple inheritance

Multilple inheritance using interface

using System;

namespace Multiple_Inheritance
{
    class Person //base class
    {

    }
    class Employee //base class
    {

    }
    class Teacher:Person,Employee  // you can not inherit 2 parent class in one child class
    {

    }
    internal class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
using System;


namespace Multiple_Inheritance
{
    class Person     // base class
    {
       public void Show1()
        {
            Console.WriteLine("This is a method of Person class");
        }
    }
    interface Employee  //interface
    {
        void Show2();
    }
    class Teacher:Person,Employee  // one parent one child and one interface   
    {
        public void Show2()
        {
            Console.WriteLine("This is a method of employee interface");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Teacher T = new Teacher();
            T.Show1();
            T.Show2();
        }
    }
}

/* output
This is a method of Person class
This is a method of employee interface
Press any key to continue . . .*/
using System;


namespace Multiple_Inheritance
{
    class Person
    {
       public void Show()
        {
            Console.WriteLine("This is a method of Person class");
        }
    }
    interface Employee // interface1
    {
        void Show();
    }
    interface Employee1 //interface2
    {
        void Show();
    }

    class Teacher:Person,Employee,Employee1 //one child class have a one parent class but uou can use multiple inheritance
    {
        void Employee.Show()
        {
            Console.WriteLine("This is a method of employee interface");
        }
        void Employee1.Show()
        {
            Console.WriteLine("This is a method of Employee1 interfaces");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Employee1 E = new Teacher();
           E.Show();        
        }
    }
}
/*  output
This is a method of Employee1 interfaces
Press any key to continue . . .
*/

A class can extends or inherits only one class a but a class can implement or inherits one or more then one interface.

In other word , a sub class can only have one parent class but a subclass can implements or inherits or one or more then one interface.

Access Modifiers:-

C# provides you with access modifiers that allow you to specify Which class can access the data members of a particular class,

OR

It's a special kind of modifers using which we can define the scope of a type and it's members.

  1. Public

  2. Private

  3. Protected

  4. internal

  5. Private Protected

  6. Protected internal

If you are decleair variable or any method decelear or class member declearing time if yor not write any access modifair there is by default is private medifair

Public (Meens no restruction) you can access the mthod any class no riestruction

Property:-

Properties Allow you to Control the Accessibility of Class Variables, And Are the Recommended way to Access variables from the outside in c#

A property is much a combination of a variable and method - it can't take any parameters, but you are to process the value before it's Assifned to returned.

Propertyies are Like Data Fields (Variables),Bit have logic behind them

From the outside, they look like any other member variable. but they act like a member function.

Defined like a field,with "get"and"set" Accessors code Added.

Properties are also used for Encapsulation

using System;


namespace Property
{

    class Student
    {
        private int _StdId;
        private string _Name;
        private string _Fname;

         public int StdId   //Firs set vale here       // Theis Call Property
        {
            set
            {
                if (value <= 0)
                {
                    Console.WriteLine("Id is not should be 0 and - negative ");
                }
                else
                {
                    this._StdId = value;// first property then it will come here  and store in value
                }

            }
            get
            {
                return this._StdId;
            }
        }
        public string Name
        {         
          set
          {
                if (string.IsNullOrEmpty(value))
                {
                    Console.WriteLine("Enter The name");
                }
                else
                {
                    this._Name=value;
                }
          }
           get
           {

            return this._Name;
           }
        }

        public string Fname
        {
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    Console.WriteLine("Father name is missing");
                }
                else
                {
                    this.Name=value;
                }
            }
            get
            {
                return this._Name;
            }
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            // Property Queation 
            Student S = new Student();
            S.StdId = 1; // this value is going to and set the StdId property
            S.Name = "Sumit";
            Console.WriteLine("Student Name :"+S.Name);

            S.Fname = "Welcome";
            Console.WriteLine("Father name is :"+S.Fname);

             Console.WriteLine( "Student id "+S.StdId );
            Console.ReadKey();
        }
    }
}

Types OF PROPERTIES IN C#

  1. READ/WRITE PROPERTIES

  2. READ ONLY PROPERTIES

  3. WRITE ONLY PROPERTIES

  4. AUTO IMPLEMENTED PROPERTIES

using System;


namespace Property
{                 // Read Only Property EX
    class STD
    {
        private int _StdId;
        private string _Name;
        private string _Fname;
        private int _SubjectTotalMarks = 100;  //here already  set the value

        //It is Read Only Property
        public int SubjectTotelMarks   //Property  // 
        {
            get                   // here only we are get the property we can not set the property 
            {
                return _SubjectTotalMarks;
            }
        }

        public string Sname
        {
            set
            {
               this._Name = value;
            }
        }
    }
    internal class Property_Types
    {
        static void Main()
        {
            STD st=new STD();
            //  st.SubjectTotelMarks = 100;  // if we are pass  or set the value it will showing error
            Console.WriteLine(st.SubjectTotelMarks); // here print only value that by it is a read only property

            // thes is a set property example
            st.Sname = "Sumit"; // here we are set only property
            //Console.WriteLine(st.Sname); //if You want print show error
        }
    }
}

AUTO IMPLEMENTED PROPERTIES:-


                          //    AUTO IMPLEMENTED PROPERTIES

using System;

namespace Property
{

    class Hello
    {
     public string FName {  get; set; }  // AUTO IMPLEMENTED PROPERTIES it is a combination of variable and property  
     public string Lname { get; set; }



    }
    internal class Property_ReadWrite
    {
        static void Main()
        {
            Hello h=new Hello();
            h.FName = "Sumit";
            h.Lname = "Gupta";
            Console.WriteLine(h.FName+" "+h.Lname);
        }
    }
}

STATIC Property:-

The Static property is used to access and manipulate static fields of class in a safe manner.

The static property declared by using the static keyword.

The static property accessed using the class name and thus,belongs to the class rather than just an instance of the class.

The static property called by a programmer without creating an instance of the class.

We cannot initilize instance fields within static property

                           //Static Property EX

using System;


namespace Property
{
     class University
    {
        private static string _UniversityName;  //static variable
        private static string _Department;

        public static string UniversityName   // Static Property
        {

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    Console.WriteLine("Enter valid Name");
                }
                else
                {
                    _UniversityName = value;
                }

            }
            get
            {
                return _UniversityName;
            }
        }

        public static string Department
        {
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    Console.WriteLine("Enter valid Name");
                }
                else
                {
                    _Department = value;
                }

            }
            get
            {
             return _Department;
            }
        }
     }

    internal class StaticProperty
    {
        static void Main()
        {
            University.UniversityName = "MakhanLal";
            Console.WriteLine("University name is: {0}", University.UniversityName);

            University.Department = "Software Engineering";
            Console.WriteLine("Department Name is: {0}",University.Department);


        }
    }
}

POLYMORPHISM

Polymorphism is one of the four pillars of object Oriented Programming.

Ploymorphism in c# is a concept by which we can perform a single action by different ways.

Polymorphism is derived form 2 Greek Word:Poly and Morphs.

The Word "poly"means many and "morphs" means forms.

so polymorphism means many forms

EX.(One Man He is a Father he is a son he is a husband Teacher)

THERE ARE TWO TYPE OF POLYMORPHISM

  1. Static Polymorphism (Compile Time Polymorphism)

  2. Dynamic polymorphism (Run time polymorphism)

STATIC POLYMORPHISM (COMPILE TIME POLYMORPHISM)

The mechanism of linking a function with an object during coppile time is called static polymorphism or early binding.

It is also called static biniding.

provides two techniques to implement static polymorphism.They are

  1. Method Or Function Overloading

  2. Operator Overloading

Method Or Function Overloading:-

You can have multiple definition for same function in the same scope.

The definition of the function must differ form each other by the types and /or the number of argument in the argument list.

You cannot overload function declaration differ only by return type.

Mehtod Overloading is create a same method name but diffrent pairameter name it called method Overloading

EX.

using System;

namespace PolymorphismExample
{
    internal class Program
    {
        public void Add()   // non parameteraized parameter Method
        {
            int a = 10;
            int b = 20;
            int c = a + b;
            Console.WriteLine(c);
        }
        public void Add(int a,int b)// diffrent parameter
        {
            int c = a + b;
            Console.WriteLine(c);
        }
        public void Add(string a, string b) // string parameter
        {
            string c = a +" "+ b;
            Console.WriteLine(c);
        }
        public void Add(float a, float b)   // diffrent parameter 
        {
            float c = a + b;
            Console.WriteLine(c);
        }

        static void Main(string[] args)
        {
          Program P=new Program();
            Console.WriteLine("-------------------");
            Console.WriteLine("First Method");
            P.Add();
            Console.WriteLine("-------------------");
            Console.WriteLine("second Method");
             P.Add(50, 50);             // passing parameter 
            Console.WriteLine("-------------------");
            Console.WriteLine("third Method");
             P.Add("Sumit","Gupta");  // passing parameter 
            Console.WriteLine("-------------------");
            Console.WriteLine("forth Method");
             P.Add(10, 10.5f);       // if you not using f so it will showing error 
            Console.WriteLine("-------------------");
            Console.ReadLine();

        }
    }
}

You cannot overload function declaration differ only by return type.

// You cannot overload function declaration differ only by return type.

using System;

namespace PolymorphismExample
{
    internal class PolyMorphism2
    {
        public void Sum(int a,int b)   
        {
            int c = a+b;

        }
        public int Sum(int a ,int b)   // it will showing error because not allow 
        {                              // you use diffrent return type
              int c=a+b;
            return c;
        }
        static void Main()
        {
            PolyMorphism2 P=new PolyMorphism2();
            P.Sum(10,20);

        }
    }
}

OPERATOR OVERLOADING:-

The concept of overloading a function can be applied to operators.

Operator overloading gives the ability to use same operator to do various operations.

It provides additional capabilties to c# operators when they are applied to user-defined data type.

It enables to make user-defined implementation of various operation where one or both of the operands are of a user-defined class

       //  Operator overloading EX

using System;

namespace PolymorphismExample
{
    class NewClass
    {
        public string str;   // instance variable
        public int num;

        //creating a new function and (operator) is compulsory
        public static NewClass operator +(NewClass obj1, NewClass obj2)  // we want to operator over loading it is importent line
        {
            NewClass obj3 = new NewClass();
            obj3.str = obj1.str +" "+ obj2.str; 
            obj3.num= obj1.num + obj2.num;
            return obj3;
        } 
    }
    internal class PolyMorphism2
    {

        static void Main()
        {
            NewClass obj1 = new NewClass(); // obj first
            obj1.str = "Sumit";
            obj1.num = 50;
                                    // i want to obj1 and obj2 boath are combain and giving the output is obj3

            NewClass obj2 = new NewClass(); // second object
            obj2.str = "Gupta";
            obj2.num = 10;


            NewClass obj3 = new NewClass();  // third object
            obj3 = obj1 + obj2;


            Console.WriteLine(obj3.str);
            Console.WriteLine(obj3.num);
        }
    }
}

Only the predefined set of c# operators can be overloaded.

To make operations on a user-defiend data type is not as simple as the operation on a built-in data type.

To use operators with user-defiend data types,they need to be overloaded accroding to a programmer's requirement.

An operatior can be overloaded by defining a function to it.

The function of the operator is declared by using the operator keyword.

Operator may be considered as function internal to the compiler.

Dynamic polymorphism (Run time polymorphism) :-

Method Overriding

If derived class defines same method as defined in its base class it is know as method overriding.

It is used to achieve runtime polymorphism.

It is enables you to provide specific implemention of the method in child class which is already provided by its base class.

To perform method overriding in c# you need to use virtual with base class method and override keyword with derived class method



//Method Overriding

using System;

namespace PolymorphismExample
{
    class parent
    {
        public virtual void Print()
        {
            Console.WriteLine("This a method of parent Class");
        }
    }
    class Child : parent
    {
        public override void Print()
        {
            Console.WriteLine("This a method child class");
        }
    }
    internal class RunTimePoly
    {
        static void Main()
        {
            parent C=new Child();
            C.Print();
        }
    }
}
  • A method decelared using the virtule keyword is referred to as a virtual method.

  • In the derived class, you need to declare the inherited virtual method using the overriding keyword.

  • In the derived class,you need declare the inherited virtual method using the override keyword which is mandatory for any virtual method that is inherited in the derived class

  • The override keyword overrides the base class method in the derived class.

Method Hiding in c# programming :-

Method hiding in inheritance relationship when base class and derived class both have a method with same name and same signature.

Whaen we create the object of derived class it will hide the base class method and will call its own method and this is called method hiding or name hiding in c# inheritance.

We use "new " keyword in derived function name to show that implementation of the function of the function in derived class is intentional and derived class no longer want to use base class method.

Note:- if we do not use "new"Keyword then compiler will raise only warning, but,program will work fine.

Different ways to call a hidden base class member From Derived Class

  1. Use Base Keyword

  2. Cast Child typy to parent type and invoke the member.

  3. ParentClass PC=new ChildClass();

    PC.hiddenMethod();



using System;

namespace PolymorphismExample
{
    class parent
    {
        public virtual void Print()
        {
            Console.WriteLine("This a method of parent Class");
        }
    }
    class Child : parent
    {
        public override void Print()
        {
           // base.Print();
            Console.WriteLine("This a method child class");
        }
    }
    internal class RunTimePoly
    {
        static void Main()
        {
            Child c =new Child();
            c.Print();
           // ((parent)C).Print();  // its work type casting
        }
    }
}

Parent Class Can Have The Refence Of its Child Class.

When we create the object of child class,parent Classs object is also created.

using System;

namespace PolymorphismExample
{
    class Employee
    {
        public string firstName;
        public string LastName;
        public void PrintfullName()
        {
            Console.WriteLine(firstName+" "+LastName);
        }
    }
    class PartTimeEmployee:Employee
    {
        public void PrintfullName()
        {
            base.PrintfullName();   // if we want call child class and method run base class we are using this type
           // Console.WriteLine( firstName + " " + LastName+" PTE");
        }
    }
    class FullTimeEmployee:Employee
    {
        public void PrintfullName()
        {
            Console.WriteLine( firstName + " " + LastName+" FTE");
        }

    }
    internal class OverREX2
    {
        static void Main()
        {
            PartTimeEmployee PTE = new PartTimeEmployee();
            PTE.firstName = "Sumit";
            PTE.LastName = "Gupta";
            PTE.PrintfullName();
            Console.ReadLine();
        }
    }
}

DIFFRENCE BETWEEN METHOD HIDING AND METHOD OVERLOADING:-

In Method Hidding,A base class reffrence variable pointing to a child class object, will invoke the hidden method of the base class

                            //Method Hiding

using System;

namespace PolymorphismExample
{
    class Employee
    {

       public void show()
        {
            Console.WriteLine("This is a parent Class Method");
        }
    }
    class PartTimeEmployee:Employee
    {
       public new void show() // using new keyword meens it will hide parent class method
        {
            Console.WriteLine("This is a childe class method");
        }
    }

    internal class OverREX2
    {
        static void Main()
        {
//Reference variable
            Employee E = new PartTimeEmployee();  // Store childe class object to parent class   if change Employee And write ParttimeEmployee then it class Child class method
            E.show();         //it will call parent
            Console.ReadLine();
        }
    }
}


/*         OutPUT
 This is a parent Class Method
*/

In Method Overloading A base class reffence variable pointing to a class child class object will invoke the overridden method of the child class

                            //Method Overloading

using System;

namespace PolymorphismExample
{
    class Employee
    {

       public virtual void show() // virtual means it showing hoide me
        {
            Console.WriteLine("This is a parent Class Method");
        }
    }
    class PartTimeEmployee:Employee
    {
       public override void show() //override means override parent class
        {
            Console.WriteLine("This is a childe class method");
        }
    }

    internal class OverREX2
    {
        static void Main()
        {
            Employee E = new PartTimeEmployee();  
            E.show();         //here child class method is run
            Console.ReadLine();
        }
    }
}


/*         OutPUT
this is a child class method
*/

SEALED CLASS :-

A sealde class is a class that prevents inheritance. ( if you use sealed class means we not create a child class )

The features of sealed class are :-

A sealed class can be declared by preceding the class keyword with the sealed keyword.

The sealed keyword prevents a class from being inherited by any other class

The sealed class cannot be base class as it cannote ne inherited by any other class. if a class tries to derived a sealed class,the c# compailer generates an error.

                          //SEALED CLASS 

using System;

namespace PolymorphismExample
{
   sealed class BaseClass  // Sealed means we not creating childe class 
    {                        
        public void show1()
        {
            Console.WriteLine("method base class.. ");
        }
    }
   class DerivedClass:BaseClass // its showing error
    {
        public void show2()
        {
            Console.WriteLine("Method derived Class..");
        }
    }
    internal class OverREX2
    {
        static void Main()
        {
            DerivedClass dc=new DerivedClass();
            dc.show1();  // it is showing wrror
        }
    }
}

sapose-> i have one parent class there have importent data i want to didn't share so i am using sealed key word it means any person dont create chaild class

Purpose of Sealed Class

-> Consider a class named SystemInformatio that consists of critcal method that affect the working of operating system.

you might not want any third party to inherit the class systeminfomation and override its method, thus, causing security and copyright issues.

Here, you can declare the systeinfomation class to prevent any change in its variables and method.

SEALED METHOD

It is only use for method overriding

When the derived class override class overrides a base class method, variable,property or event, then the new method, variable, property,or event can be declared as sealed.

Sealing the new method prevents the method from further Overriding

An overriding method can be sealed by preceding the override keyword with the sealed keyword.

                          //SEALED METHOD

using System;

namespace PolymorphismExample
{
   class A
    {
        public virtual void Print()
        {
            Console.WriteLine("This is a method of the A class ");
        }
    }
    class B:A
    {
        public  sealed override void Print()  // here using sealed keyword means B class method not be inherit
        {                                     // here sealed and override borth are write so it will work it
            Console.WriteLine("This is a method of B class");
        }
    }
    class C:B
    {
        public override void Print()  // here its showing error because not be inherit
        {
            Console.WriteLine("This is a method of c class");
        }
    }
    internal class OverREX2
    {
        static void Main()
        {
            C Obj = new C();
            Obj.Print();
            Console.ReadLine();
        }
    }
}

STEPS TO REMEMBER FOR SEALED METHOD:

Sealed method is an override method of child class.

we cannot again override the sealed method.

sealed method is only available with method Overriding.

Sealed keyword is not available with the method hiding.

Sealed is used together with override method.

We cannot make normal method as sealed.

INDEXER :-

Indexers allow our boject to be used just like an, or we can say index the object using[]brackets just like array.

->We can say indexer are specail type of propertes which adds logic that how can array or list store the value.

Syntax of indexer resembles to properties.

We can use all access modifiers with indexer and also have return types.

Indexer are the regular member of a class.

Index is creatd with the help of this keyword.

// Indexer declaration
[<modifiers>] <type> this[<parameter list>]
{
    [get{<stmts>}] //Get Accessor
    [set{<stmts>}] //Set Accessor
}
class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass();

        // Using the indexer to set values
        obj[0] = 10;
        obj[1] = 20;

        // Using the indexer to get values
        Console.WriteLine(obj[0]); // Output: 10
        Console.WriteLine(obj[1]); // Output: 20
    }
}
                        // Indexer

using System;


namespace PolymorphismExample
{
    class Employee
    {
        private int[] Age = new int[3];
        public int this[int index]    //indexer this repels with object name emp
        {                             // and [int index] it is a parameter in indexer one parameter is manitry if you not give any parameter so it will show compaile time error
            set
            {
                if (index >= 0 && index < Age.Length)
                {

                    if (value > 0)
                    {
                        Age[index] = value;
                    }

                    else
                    {
                        Console.WriteLine("Value is invalid !!");
                    }
                }
                else
                {
                    Console.WriteLine("Invalid Index");
                }

            }
            get
            {
                return Age[index];
            }
        }
    }
    internal class Indexer
    {
        static void Main()
        {
            Employee emp = new Employee();
            emp[2] = 5; // it will store value keyword
           Console.WriteLine(emp[2]);
        }
    }
}
  • Indexer Concept is object act as an array.

  • Indexer an object to be indexer in the same way as an array.

  • Indexer modifier can be private, public, protected or internal.

  • The return type can be any valid c# type.

  • Indexer in c# must have at least one parameter. Else Compailer will generate a compailation erro

       // Indexer Overloading

using System;
namespace PolymorphismExample
{
    class Employee
    {
        private int[] Age = new int[3];
        public int this[int index, int i]
        {
            set 
            { 
                Age[index] = value + i;
            }
            get
            {
                return Age[index];
            }

        }

        public int this[int index]    
        {
            set
            {
                if (index >= 0 && index < Age.Length)
                {

                    if (value > 0)
                    {
                        Age[index] = value;
                    }

                    else
                    {
                        Console.WriteLine("Value is invalid !!");
                    }
                }
                else
                {
                    Console.WriteLine("Invalid Index");
                }



            }
            get
            {
                return Age[index];
            }
        }
    }
    internal class Indexer
    {
        static void Main()
        {
            Employee emp = new Employee();
            emp[0, 1]= 5;
           Console.WriteLine(emp[0]);

        }
    }
}

Delegate:-

Delegate is a type that represent reference to method with a specific parameter list and return type.

A delegate is a reference to the method.

or

It is a type safe function pointer.

-Adelegate holds the reference of a method and then calls the method for execution.

using System;


namespace DelegateEX
{
    public delegate void Calculation(int num1, int num2);
    class Program
    {
      public static void Addition(int num1,int num2) //here we are change the name no problem
        {
            int result = num1 + num2;
            Console.WriteLine("Addition result is : ",result);
        }
        public static void Subtraction(int num1,int num2)
        {
            int result = num1 - num2;
            Console.WriteLine("Result is subtraction: " +result);
        }
        public void Multiplication(int num1, int num2)
        {
            int result=num1 * num2;
            Console.WriteLine("Multiplication is: "+result);
        }
        public void Divide(int num1,int num2)
        {
           int result =num1 / num2;
            Console.WriteLine("Divide result is "+result);
        }
        static void Main(string[] args)
        {
           Calculation C=new Calculation(Subtraction);
            // C(500,100);
            C(100, 50);
            Console.ReadLine();
        }
    }
}

Type of delegate:-

-> Single Cast delegate

-> Multipal cast delegate

-> Multi Cast delegate

Single Cast delegates:

Singlecast delegate point to method at a time in this the delegate is assigined to a single method at a time. They are derived form System.Delegat class.

                        // Single Cast Delegate

using System;
namespace DelegateEX
{
    public delegate void Calculation(int num1, int num2);
    class Program
    {
      public static void Addition(int num1,int num2) //here we are change the name no problem
        {
            int result = num1 + num2;
            Console.WriteLine("Addition result is :{0}",result);
        }
        static void Main(string[] args)
        {
           Calculation C=new Calculation(Addition);
            C(50,100);
            Console.ReadLine();
        }
    }
}

Mulltiple Delegate:-

In c#, a user can invoke multiple delegate within a single program. Depending on the delegate name or the type or parameters passed to the delegate, the appropiate delegate is invoked.

             // Mulltiple delegate

using System;


namespace DelegateEX
{         //delegate
    public delegate void Calculation(int num1, int num2);
    public delegate void show_detegate(); // it will coll only parameter les function and return type is same like void
    public delegate void QubSqr(int num);
    class Program
    {

        public static void Square(int num)
        {
            int square = num*num;
            Console.WriteLine("square is "+square);
        }

        public static void Qube(int num)
        {
            int qube = num*num*num;
            Console.WriteLine("cube is "+qube);
        }


        public static void Show()
        {
            Console.WriteLine("This is a Show method !!");
        }


      public static void Addition(int num1,int num2) //here we are change the name no problem
        {
            int result = num1 + num2;
            Console.WriteLine("Addition result is : ",result);
        }
        public static void Subtraction(int num1,int num2)
        {
            int result = num1 - num2;
            Console.WriteLine("Result is subtraction: " +result);
        }
        public void Multiplication(int num1, int num2)
        {
            int result=num1 * num2;
            Console.WriteLine("Multiplication is: "+result);
        }
        public void Divide(int num1,int num2)
        {
           int result =num1 / num2;
            Console.WriteLine("Divide result is "+result);
        }
        static void Main(string[] args)
        {
            //Calculation C=new Calculation(Subtraction);
            // // C(500,100);
            // C(100, 50);
            //show_detegate S = new show_detegate(Show);
            //S.Invoke();

            QubSqr Q = new QubSqr(Square);
            Q.Invoke(5);
            Q = Qube;
           // QubSqr Q1 = new QubSqr(Qube);
            Q.Invoke(3);

            Console.ReadLine();
        }
    }
}

Multi cast Delegate:-

When a delegate is wrapped with more then one method that is known as a multicast delegate.

In c#, delegate are multicast, which means they can point to more then one function at a time. They are derived form System.Multicast Delegate class.

We can use += and -= assignment operators to impliment multi cast delegate.

             // Multicast delegate

using System;


namespace DelegateEX
{
    public delegate void Calculation(int num1, int num2);

    class Program
    {
      public static void Addition(int num1,int num2) 
        {
            int result = num1 + num2;
            Console.WriteLine("Addition result is : "+result);
        }
        public static void Subtraction(int num1,int num2)
        {
            int result = num1 - num2;
            Console.WriteLine("Result is subtraction: " +result);
        }
        public static void Multiplication(int num1, int num2)
        {
            int result=num1 * num2;
            Console.WriteLine("Multiplication is: "+result);
        }
        public static void Divide(int num1,int num2)
        {
           int result =num1 / num2;
            Console.WriteLine("Divide result is "+result);
        }
        static void Main(string[] args)
        {
            Calculation obj = new Calculation(Addition);
            obj += Subtraction;
            obj += Multiplication;            // here we are use this type
            obj -= Divide;  //  -= it will not showing divide result
            obj(30,10);           

            Console.ReadLine();
        }
    }
}
/*out put is 
 Addition result is : 40
Result is subtraction: 20
Multiplication is: 300
*/

ANONYMOUS FUNCTION :-

We discussed that delegate are used to reference any method that has the same signatture as that of the dekegate.

As the name suggests,an anonymous method is a method without a name juse the body.

Anonymous method in c# can be defined using the delegate keyword.

It is intrudused in 2.0.

               // Anonimous

using System;

namespace DelegateEX
{
    public delegate int MyDeligate(int num);

    internal class Anonimus1
    {
        //public static void MyMethod(int a)
        //{
        //    a += 10;
        //    Console.WriteLine(a);
        //}
        static void Main()
        {
            MyDeligate obj = delegate (int a)    // it is a anonimous method  it have a body it have a same return type a delegate
            {
                a += 10;
                // Console.WriteLine(a);
                return a;

            };                 // semicolon is manotery
           // obj.Invoke(5);    //if you don't want to using invoke method so your are write like obj(5) no problem

            Console.WriteLine(obj.Invoke(5));

        }
    }
}
  • Anonimous method can be assigned to a variable of delegate type.

  • You need not specify the return type in anonymous method;it is inferred form the return statement inside the method body.

  • We don't requried to use access modifiers with anonymous function like public,private etc

  • We don't required to use return type like int,string because its return is as same as delegate type.

  • Anonymous function is not a static and instance member.

  • Q. What is your anonymous function return type

  • ANS your delegate return type is same a anonymous function return type

Advantages of anonymous function

Lesser typing work because we don't requried to write access modifier, return type and name of the function.

Anonymous function are suggested when code volumes are less.

Limitation:-

It cannot contain jump statement like goto,breakor continue,

It cannot access ref or out parameter of outer method

Points To Remember:-

Anonymous method can be defined using the delegate keyword

Anonymous method must be assigned to a delegate.

Anonymous method can access outer variables or functions.

Anonymous method can be pass as a parameter

Lambda Expression

In C#, lambda expressions provide a simple syntax for composing anonymous functions or methods. They are shortcuts for defining expressions or delegates that may be assigned to variables or passed as arguments to methods.

                       // This is a Anonimous function

using System;
namespace LambdaEx
{
    public delegate void MyDelegate(int  num);
     class Program
    {
        static void Main(string[] args)
        {
            MyDelegate obj = delegate (int a)   //its call anonymous function
            {
                a += 5;
                Console.WriteLine(a);
            };

            obj.Invoke(5);
            Console.ReadLine();
        }
    }
}

Lambda Expression:-

                   //its call Lambda Expression

MyDelegate obj = (a) =>      // => its call lambda Operator
{ 
    a += 5;
    Console.WriteLine(a);
};

It is also work like an anonymous method.

The difference that in Lambda expression you don't need to specify the type of the value that you input thus making it more fiexible to use.

It means lambda expression simlifies the anonymous function or you can say that lambda expression is a shorthand for an anonymous function.

The => is lambda operator which is use in all lambda expressions.

The Lambda Expression is divided into two parts,the left side is the input and the right is the expression.

Types of lambda expression

The lambda Expressions can be two types:

  1. Statement LambdaThe L: Consists of the input and a set of statements to be executed.

    Syntax:

    input =>

    {

    statement

    };

    Note:Dose not return any value implicitly

In the lambda expression have a {} its meen it is a Statement lambda

  1. Expression lambda: Consists of the input and the expression.

    Syntax:

    input => expression; //here we write only one line expression and no {}

Not : Returns the evaluated value implicitly,

Abstract Class:-

Abstract Class: A class that has any abstract members is called an abstract class

The word abstract means a concept or an idea not associated with any specific instance(object). Inprogramming we apply the same menning of abstraction by making classes not associtade with any specific instance

The abstraction is done when we need to only inherit form a certain class,but not need to instance object of that class,

abstract class Person  // if you use abstract class you use abstarct keyword and 
{                       // method method also write abstract key word
    public abstract void show();  // you not create a body abstract method
}
  1. C# Abstract classes are used to declare common characteristics of subclasses.

  2. A class which contains the abstract keyword in its declaration is known as abstract class.

  3. It can only be used as Base class for other classes that extend the abstract class.

  4. Abstract class may or may not contain abstract method, i.e,

  5. method without body (public void get());

  6. Like any other class, an abstract class can contain fields that describe the characteristics and method that describe the actios that a class can perform.

  7. If a class is declared abstract,it cannot be instantiated.

  8. To use an abstract class,you have to inherit it form another class provide implementation to the abstract method in it

  9. If you inherit an abstract class, you have to provide implementations to all the abstract method in it.

  10. An abstract class can implement code with non-Abstract Method.

  11. An Abstract Class can have modifiers for method,properties etc.

  12. An Abstract class can have constants and fields.

  13. An Abstract class can impliment a property.

  14. An Abstract class can have constructor or destructors

using System;

namespace AbstractClassEX
{
    abstract class Person    // abstract class
    {
        public string Firstname;
        public string Lastname;
        public int age;
        public long phonNumber;

        public abstract void PrintDetalis();  // abstract method we can also creatr simple method

    }
    class student: Person   // inherite
    {
        public int RoolNumber;
        public int fees;

        public override void PrintDetalis()  // use abstract method but overriding is manytry
        {
           string name=this.Firstname+" "+Lastname;
            Console.WriteLine("student name is :"+name);
            Console.WriteLine("Student Age is  :"+this.age);
            Console.WriteLine("Student Phon no :"+this.phonNumber);
            Console.WriteLine("student Roll Number is :"+this.RoolNumber);
            Console.WriteLine("Student fees"+this.fees);
        }

    }
    class Teacher: Person
    {
        public string qualification;
        public int salary;
        public override void PrintDetalis()
        {


            string name = this.Firstname + " " + Lastname;
            Console.WriteLine("Teacher name is :" + name);
            Console.WriteLine("Teacher Age is  :" + this.age);
            Console.WriteLine("Teacher Phon no :" + this.phonNumber);
            Console.WriteLine("Teacher qualification is :" + this.qualification);
            Console.WriteLine("Teacher salary " + this.salary);
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            student S = new student();  // student class object
            S.Firstname = "Sumit";
            S.Lastname = "Gupta";
            S.age = 21;
            S.phonNumber = 123456678;
            S.RoolNumber = 12;
            S.fees = 2000;
            S.PrintDetalis();
            Console.WriteLine("--------------------------");

            Teacher T = new Teacher();  // Teacher class object
            T.Firstname = "Mahesh";
            T.Lastname = "Babu";
            T.age = 45;
            T.phonNumber = 987654321;
            T.qualification = "B-teck";
            T.salary = 60000;
            T.PrintDetalis() ;

            Console.ReadLine();
        }
    }
}

ABSTRACT PROPERTIES

The word Abstract Means incomplete,which means no implementation in programming.

This is duty of child class to implement an member of their parent class.

Declared by using the abstract keyword.

Contain only the declaration of the property without the body of the get and accessors (Which do not contain any statements and can be Implemented in the derived class).

Are only Allowed in an abstract class.

                    // Abstract Property
using System;

namespace AbstractClassEX
{
    abstract class person
    {
        public abstract uint id { get; set; }  // its call abstract prpperty we can only create abstract property its use childe class
        public abstract string Name { get; set; }

    }
    class Student : person
    {
        int StudentId;
        string StudentName;

        public override uint id
        {
            set
            {
                if (id > 0)
                {
                    Console.WriteLine("Number not should be 0 and negetive");
                }
                else
                {
                    StudentId = Convert.ToUInt16(value);  // if you use (uint) then you need to convet same like
                }

            }
            get
            {
                return Convert.ToUInt16(StudentId);
            }
        }
        public override string Name
        {
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    Console.WriteLine("Name should not be null");
                }
                else
                {
                    this.StudentName = value;
                }

            }
            get
            {
                return this.StudentName;

            }
        }

    }
    internal class AbstractPropertyEX
    {
        static void Main()
        {
            Student S=new Student();
            S.id = 1;
            S.Name ="";

            Console.WriteLine(S.id);
            Console.WriteLine(S.Name);
            Console.ReadLine();
        }
    }
}

INTERFACE:

Class:it's a user-defined data type.

Interface:this is also an user-defined data type only.

Class: non -Abstract Method (Method with method body)

Abstract Class: Non-Abstract Methods (Method with method body) and also Abstract Method (Method with out method body)

Interface:

A user-defined data type that contains only abstract methods (methods without a body). Interfaces cannot be created and are used to define a contract that classes can implement.

Interface: Contain only Abstract Method (Method Widthout Method body)

Note: Every abstract method of an interface should be implemented by the child class of the interface with out fail (Mandatory)

-Generally a class inherites form another class to consume the member of its parent,where as if a class is inheriting form an interface it is to implement the member of its parent

Note: A class can inherit form a class and interface at a time.

SYNTAX:

[<modifiers>] class <Name>

{

-Define Members here

}

[<modoifier>] interface <Name>

{

-Abstract Member

}

-The default scop the member of an interface is public wheres it's private in case of a class.

-By default every member of an interface is an interface is abstract so we don't require to use abstract modifier on it again just like we do in case of abstract class

public abstract void Add(int a,int b);

-we can't declare any fields/variables under an interface

-> If required an interface can inherit form another interface can inherit form another interface.

Every member of an interface should be implemented under the child class of the interface with out fail, bur while implementting we donr require to use overrider modifier just like have done in case of abstract class.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static InterFace.ItestInterface;

namespace InterFace
{
    internal interface ItestInterface
    {
        void Add(int a, int b); 
    }

    interface IMyInterFace1 : ItestInterface
    {
        void Sub(int a, int b);
    } 
    class ImplimentionClass: IMyInterFace1
    {
        public void Add(int a ,int b)
        {
            Console.WriteLine(a+b);
        }
        public void Sub(int a, int b)
     {
            Console.WriteLine(a-b);
        }
        static void Main()
        {
           // ImplimentionClass obj= new ImplimentionClass();
           IMyInterFace1 obj2 = new ImplimentionClass();    // here we are use boath technic 
            obj2.Add(30,20);
            obj2.Sub(30,20);

          //  obj.Add(20, 10);obj.Sub(100,50);
        }
    }
}

INTERFACE INHERITANCE :-

Interface can inherit form other interfaces.

A class that inherits this interface must provide implementation for all interface member in the entier interface inheritance chain.

Interface reference variable can have the reference of their child class.

using System;

namespace InterfaceInheritanceExample
{
    // Base interface 1
    interface IVehicle
    {
        void Start();
        void Stop();
    }

    // Base interface 2
    interface IFlyable
    {
        void Fly();
    }

    // Derived interface that inherits from both IVehicle and IFlyable
    interface IAirplane : IVehicle, IFlyable
    {
        void Land();
    }

    // Class that implements the derived interface IAirplane
    class Airplane : IAirplane
    {
        // Implementing the Start method from IVehicle
        public void Start()
        {
            Console.WriteLine("Airplane is starting.");
        }

        // Implementing the Stop method from IVehicle
        public void Stop()
        {
            Console.WriteLine("Airplane is stopping.");
        }

        // Implementing the Fly method from IFlyable
        public void Fly()
        {
            Console.WriteLine("Airplane is flying.");
        }

        // Implementing the Land method from IAirplane
        public void Land()
        {
            Console.WriteLine("Airplane is landing.");
        }

        // Main method to test the Airplane class
        static void Main(string[] args)
        {
            Airplane myAirplane = new Airplane();

            myAirplane.Start();  // Calls the Start method from IVehicle
            myAirplane.Fly();    // Calls the Fly method from IFlyable
            myAirplane.Land();   // Calls the Land method from IAirplane
            myAirplane.Stop();   // Calls the Stop method from IVehicle
        }
    }
}

EXPlICIT INTERFACE IMPLEMENTATION :-

There are 2 type of implementaion of interfaces.

Implicit interface Implimentaion.

Explicit interface Implementaion.

-> A class has to explicitly implement multiple interface if thes interfaces have methods with identical names.

If an interface has a method name idential to the name of a method declared in the inheriting class, this interface has to be explicitly implemented.

                  //Implicit interface Implimentasion

namespace InterfaceEx2
{
    interface I1
    {
      void Show();
    }

    class myClass : I1
    {
     public void Show()
        {

        }       
    }
                       // Explicit interface implimentasion



using System;

namespace InterfaceEx2
{
    interface I1
    {
      void Show();
    }

    interface I2
    {
        void Show();
    }
    class myClass : I1,I2
    {
        void I1.Show()   //if you ise Explicit implimentaion the you not need pusing public it is also public only explicit Impliment 
        {
            Console.WriteLine("This is a method of i1 interface");
        } 

        void I2.Show()
        {
            Console.WriteLine("This is a method of i2 interface");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            //myClass obj =new myClass(); 
            //((I1)obj).Show();  //it is a Explicit Implimentasion
            //((I2)obj).Show();

            I1 obj1= new myClass(); // pairent ka refrence variable ke ander childe ka object rakh sakte hai
            obj1.Show();

            I2 obj2= new myClass();
            obj2.Show();
            Console.ReadLine();
        }
    }
}
                 // Implicit and explicit boath are use in one program
using System;
namespace InterfaceEx2
{
    interface I1
    {
      void Show();
    }



    interface I2
    {
        void Show();
    }
    class myClass : I1,I2
    {
       public void Show()   //if you use Impliment  then you need public access modifair
        {
            Console.WriteLine("This is a method of i1 interface");
        } 

        void I2.Show()
        {
            Console.WriteLine("This is a method of i2 interface");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
           I1 obj=new myClass();  // it is a implicit 
            obj.Show();

            myClass M = new myClass();  // it is a  Explicit 
            ((I2)M).Show();
        }
    }
}

Similarities Between Abstract Classes And Interfaces

Abstract classes and interfaces both declare methods without implementing them.

-> Both,abstract classes as well as interfaces,contain abstract Methods.

->Abstract Method of both, the abstract class as well as the interface, are implemented by the inheriting subclass.

-> Both,abstract classes as well as interfaces,can inherit multiple interfaces.

-> We can not create a object abstract class and interface But We can create refrence

DIFFRENTIATE BETWEEN ABSTRACT CLASS AND INTERFACES:

ABSTRACT CLASSINTERFACE
An abstract class can inherit a class and multiple interfaceAn interface can inherit multiple interface but cannot inherit a class.
An abstract class can have methods with method bodyAn interface can not have method with a body
An abstract class method is implemented using the override keywordAn interface method is implemented without using the override keyword.
An abstract class is a better option when you need to implement common method and declare common abstract methods.An interface is a better option when you need to declare abstract methods.
An abstracts class can declare constructor and destroctorAn interface cannot declare constructor or destructors.
If you want to declare an abstract member in abstract class then abstract keyword is mandatoryif you want to declare an abstract member in interface then abstract keyword is not mandatory because members of interface are abstract by default.
  1.                                      // first difrence Result Abstract class
                        namespace InterfaceEx2
                        {
                           abstract class Example
                            {
    
                            }
                            interface i1
                            {
    
                            }
                            interface i2
                            {
    
                            }
                           /* abstract class Example2
                            {
    
                            }*/
                            class myclass:Example,i1,i2 // we can not inherit 2 abstract class in one childe class
                            {                           
    
                            }
    
         // first difrence Result interface 
abstract class Example
 {

 }
interface i1
{
}
interface i2
{
}
 interface i3:Example // you can not inherit class in interface it wil showing error
 {

 }

                      //  but
interface i3:i1,i2 // interface inherit multiple interfaces it will not showing error
{

}
  1.                       abstract class Example  // we can create a method body in abstract classs
                           {
                               public void meth()
                               {
    
                               }
                           }
                           interface i1
                           {
                               void Meth()   // we can not creat method body in in interface it is not allowed
                               {
    
                               }
                           }
    

    3

  using System;
  using System.Security.Permissions;


  namespace InterfaceEx2
  {
      abstract class Person
      { 

      }
      interface i1
      {

      }
      interface i2
      {

      }
       interface MyInterface:i1,i2
       {
          void print();
       }

      abstract class myclass : Person, i1,i2
      {
          public abstract void show();
      }
      class MyClass_1 : myclass,MyInterface
      {
          public override void show() //if you use abstract class method then override keyword is importent
          {

          }
          public void print()   // if you override interface method then you not need override keyword
          {
              Console.WriteLine("This is a method of interface ! !");
          }
      }

DIFFERENTIATE BETWEEN ABSTRACT CLASSES AND INTERFACES IN C#

ABSTRACT CLASSINTERFACE
An abstract class can inherit a class and multiple interfaces.An interface can inherit multiple interfaces but cannot inherit a clsss.
An abstract class can have method with a bodyAn interface cannot have method with a body
An abstract class method is implemented using the override keyword.An interface is a better option when you need to declare only abstract method.
An abstract class can declare constructor and destructorAn interface cannot decclare constors or destructors.
An abstract class is a better option when you need to implement common methods and declare common abstract methods.An interfaces is a better option when you need to declare only abstract method
If you want to declare an abstract member in declare an abstract class then abstract keyword is mandatory.If you want to declare an abstract member in interface then abstract keyword is not mandatory because members of interface are abstract by default.

GENERIC CLASS :-

Genaric classes definition functionalities that can be useful for any data type and are declared with a class declaration followed by a type parameter enclosed within angular brackets.

Generics introduced in C#2.0. Generics allow you to define a class with placeholders for the type of its fields, methods, parameters etc. Generic replace these placeholders with some specific type at compile time.

Syntax :

Class A <T>

{

}

                               //Genric class 
using System;

namespace GenricClass
{
    class Example<T> // define Genric class  <T> called Type parameter and also called placeholder
    {
        T box;    // here you write all time int or other data type but in genric class you write <T>
        public Example(T b)  //here also same like <T>
        {
            this.box=b;
        }
        public T getBox()
        {
            return this.box;
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Example<int> E = new Example<int>(20);  //here perform multiple task like Thah <T> we are diffine in object in which type data is store
            Example<string> E1 = new Example<string>("Sumit");
            Example<char> E2 = new Example<char>('A');
            Console.WriteLine(E.getBox());
            Console.WriteLine(E1.getBox());
            Console.WriteLine(E2.getBox());
            Console.ReadKey();
        }
    }
}

/* OutPut 
    20
    Sumit
    A

*/

We can use same thing inusing a property

using System;

namespace GenricClass
{
    class Example<T>
    {
        T box;
        public T Box  // Property 
        {
            set
            {
                this.box = value;
            }

            get
            {
                return this.box;
            }
        }  
    }
    internal class Program
    {
        static void Main(string[] args)
        {

            Example<int> e = new Example<int>(); // in class <T> creating object time we are difine which type store data 
            Example<string> e2 = new Example<string>();
            e.Box = 20;
            e2.Box = "Rahul";
            Console.WriteLine(e.Box);
            Console.WriteLine(e2.Box);
            Console.ReadKey();
        }
    }
}
/* Output
20
Rahul
*/

Collectoion:-

Array: It is a collection of homogeneous(similer type data) elements

or

A collection is a set of related data taht may not necessarily belong to the same data type that can be set or modifiied dynamically at run-time.

In other words, collection is a dynamic array.

  • Its Length can increase on runtime. Auto Resizing

Collection: It is a collection of heterogeneous(Different data type) elements.

Collection Introduse in c# 1.0

We have two kind of collections.

Non-Generic Collections.

  • ArrayList,Stack,Hastable,Stack,Queue,etc.

  • System.Collection namespace have non-generic collections.

Generic Collections.

  • List<T>,LinkedList<T>,Queue<T>,SortedList<T,V>.

  • System.Collection.Generic namespace have generic collection

Diffrence between Array and Collection

ArrayCollection
Cannot be resized at run-time.can be resized at run-time.
The individual elements are of the same data typeThe individual elements can be different data types.
Do not contain any methods for operation on elements.Contain method for operation on elements.
We can never insert a value into a middle of an array.We can insert a value into a middle of a collection.
We can never delete a value from a middle of an array.We can delete a value from a middle of a collection.
Ceneric collection (new)Non-generic collection (old)
List<T>and LinkedList<T>ArrayList
Dictionary<TKey,TValue> and SortedDictionary<TKey,TValue>HashTable
Queue<T>Queue
Stack<T>Stack
SortedList<Tkey,TValue>
HashSet<T> and SortedSet<T>
Array[]

Array List:-

Normal Array's lengthis fixed , it means we cannot change the length after declaring an array.

Array.Resize() but it distroy old memory

Resiz method of an array destroys old array and create a new array with new length.

-> We can never insert a value into a middle of an array, because if we want to do this then array length should be increased but we cannot increase the lingth of an array after declaring the length of an array.

-> We can naver delete a value form a middle of an array.

Accessing collection is similar to accessing arrays, where element are accessing by their index numbers. However, there are differences between arrays and collection

Difference Array and ArrayList

ArrayArrayList
Array can store only elements of the same data types.ArrayList can store elements of different data types.
Arrays cannot accept null valuesArrayList can accept null values.
Arrays are available in System.Array namespaceArrayLists are available in System.Collections namespace
We can not pass value in medileWe can pass value in medile
It is a fixed LengthIt is not a fixed length
using System;
using System.Collections;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ArrayList MyList=new ArrayList();  
            MyList.Add(10);
            Console.WriteLine(MyList.Capacity);  // by default capaycity is a 4 

        }
    }
}

//Out put  4
      static void Main(string[] args)
      {
          ArrayList MyList=new ArrayList(2);  // if you wan to change to capycity then wrete in bract you write any number then capycity start that number
          MyList.Add(10);
          Console.WriteLine(MyList.Capacity);   

      }

//Here count will start 2
using System;
using System.Collections;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ArrayList MyList=new ArrayList();  
            MyList.Add(10);
            MyList.Add(20);       
            MyList.Add(30);
            MyList.Add("Sumit");
            MyList.Add('S');
                                               //if you use like int then you print data only inteser value only
            foreach (object obj in MyList)     // And if you Print data Like inteser and string char any type then you use object
                                               // Because object store any data type
            {
                Console.WriteLine(obj);
            }

        }
    }
}
///*OutPut 
//10 20 30 Sumit S
                               //Add new value
using System;
using System.Collections;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ArrayList MyList=new ArrayList();  
            MyList.Add(10);
            MyList.Add(20);        // i  wan't to insert the data after 20 (25)
            MyList.Add(30);
            MyList.Add("Sumit");
            MyList.Add('S');

            foreach (object obj in MyList)     
            {
                Console.Write(obj+" ");
            }
            Console.WriteLine();
            Console.WriteLine();
            MyList.Insert(2, 25);
            foreach (object obj in MyList)     // And if you Print data Like inteser and string char any type then you use object                                               // Because object store any data type
            {
                Console.Write(obj+" ");
            }
        }
    }
}

/*OutPut 
10 20 30 Sumit S

10 20 25 30 Sumit S   // here insert value 25
*/
                        //Remove function
using System;
using System.Collections;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ArrayList MyList=new ArrayList();  
            MyList.Add(10);
            MyList.Add(20);        // i  wan't to insert the data after 20 (25)
            MyList.Add(30);
            MyList.Add("Sumit");
            MyList.Add('S');

            foreach (object obj in MyList)     
            {
                Console.Write(obj+" ");
            }
            Console.WriteLine();
            Console.WriteLine();
            MyList.Insert(2, 25);
            foreach (object obj in MyList)     // And if you Print data Like inteser and string char any type then you use object                                               // Because object store any data type
            {
                Console.Write(obj+" ");
            }
            Console.WriteLine();
            Console.WriteLine();
            MyList.Remove(20);          // here you enter that number the number you want to remove
            MyList.RemoveAt(4);      // you use this function then enter index number
            foreach (object obj in MyList)     // And if you Print data Like inteser and string char any type then you use object                                               // Because object store any data type
            {
                Console.Write(obj + " ");
            }
            Console.ReadKey();
        }
    }
}
/*  Out Put 
10 20 30 Sumit S

10 20 25 30 Sumit S

10 25 30 Sumit
*/

HASTABLE COLLECTION

HashTable stores data oin key/value format.

Array and ArrayList also stores data in key/value(key means index number [0][1][2]this type) format.

In Array or ArrayList Keys are pre-defined i-e index numbers, it means you cannot explicitly define keys in Array or ArrayList.

In Hastable,Keys are not pre-difined it means you can explicitly define user-defined keys(int keys,float keys,char keys ) in HashTable.

C# includes Hashtable Collection in System.Collections namespace.

The Hashtable class represents a collection of jey-and-value pairs that are organized based on the hash code of the key.

It use the key to access the elements in the collection.

using System;
using System.Collections;   // it is a important namespace it is manatry

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();

            ht.Add("Id", 1123);               //here id is a key and 1123 is a value
            ht.Add("Name", "Adil");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);
            Console.WriteLine(ht["Id"]);  // here you write like a index number 
            Console.WriteLine(ht["Name"]);
            Console.WriteLine(ht["Salary"]);
            Console.ReadLine();
        }
    }
}

/*Output 
1123
Adil
25000
*/
using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable()  //creating a object
            {
                {"Id",1123 },
                {"Name","Sumit" },
                {"Age",21 }
            };

            Console.WriteLine(ht["Age"]);  // we can access this tpye also
            Console.ReadLine();
        }
    }
}

/* output
 21
*/

A Hash table is used when you need to access elements by using key, and you can identify a useful key value.

Each item in the hash table has a key/value pair.The key is used to access the items in the collection.

Method of Hash Table

Add: Adds an item with a key and value into the hashtable.

Remove: Removes the in=tem with the sepecified key form the hashtable

Clear: Method: Remove All the items form the hastable.

Contains: Checks whether the hastable contains a specific key. {it will give value booliyan (Like True and false) same work ContainsKey}

ContainsKey: Checks whether the hastable contains a sepecific key.{it will give value booliyan (Like True and false) same work Contains}

                        // you can write this type also
using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Adil");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);

            foreach (object key in ht.Keys)
            {
                Console.WriteLine(key+" : "+ ht[key]);
            }



            Console.ReadLine();
        }
    }
}
                          //You can access this type data also

using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add(101, 1123);              
            ht.Add(102, "Adil");
            ht.Add(103, 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);

            Console.WriteLine(ht[101]);
            Console.WriteLine(ht[102]);
            Console.WriteLine(ht[103]);

            Console.ReadLine();
        }
    }
}

You wont boath are print then

using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Adil");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);

            // if you want to print value then change key(value) and Keys(value) boath side change
            foreach (object key in ht.Keys)  // here we are use Keys(mens it will showing only key Like id,Name,salary) and we also use value it will shoing value 1123,Adil,25000.00
            {
                //Console.WriteLine(ht[key]);
                //Console.WriteLine(ht[value]);
                Console.WriteLine(key+" : "+ ht[key]);
            }
            Console.ReadLine();
        }
    }
}

Remove method : Remove the item with the specified key form the hastable.

                        // using Remopve method
using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Adil");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);


            foreach (object key in ht.Keys)
            { 
                Console.WriteLine(key+" : "+ ht[key]);
            }
            ht.Remove("Salary");                     //Remove Method  Remove the Salary
            Console.WriteLine("-----------------------------");
            foreach (object key in ht.Keys)
            {
                Console.WriteLine(key+" : "+ht[key]);
            }


            Console.ReadLine();
        }
    }
}
/*Output
IsMarrid : False
Designation : Manager
Name : Adil
Id : 1123
Salary : 25000
-----------------------------
IsMarrid : False                     
Designation : Manager
Name : Adil            // salary is Remove
Id : 1123 */

Clear: Method: Remove All the items form the hastable.

using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Adil");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);


            foreach (object key in ht.Keys)
            { 
                Console.WriteLine(key+" : "+ ht[key]);
            }
            ht.Clear();
            Console.WriteLine("-----------------------------");
            foreach (object key in ht.Keys)
            {
                Console.WriteLine(key+" : "+ht[key]);
            }


            Console.ReadLine();
        }
    }
}

/*Output
IsMarrid : False
Designation : Manager
Name : Adil
Id : 1123
Salary : 25000
-----------------------------
                                                //Here Rempve all the data second Time









*/

Contains:ContanKey

using System;

using System.Collections;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Adil");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);
                        //     ContainKey    same work
            Console.WriteLine(ht.Contains("Name"));  //if name key is avilable it will show True

         Console.WriteLine("----------------------------------");
      //  Console.WriteLine(ht.ContainsValue("Adil"));  //  This methopd work only values 
            Console.ReadLine();
        }
    }
}

/*  output
True */

HASH CODE:-

// if you wont ane value any key hash code then you use getHashCode(); Method

Hash Table used Hashing algorithem To generate hash code for every key And because of these hash codes Hash table are faster then Array and ArrayList

"Name"="Sumt" { "Name" is a Key and "Sumit is a Value" }

HASHCODE -> INTEGER VALUE -> 654322 //hashcode genret the code

using System;

using System.Collections;
using System.Runtime.InteropServices;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Sumit");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);

            // Console.WriteLine(ht.Contains("Name"));

            Console.WriteLine("Sumit".GetHashCode());   // it will show hascode

            Console.ReadLine();
        }
    }
}

/* output
1188813520    // it will showin this type value
*/

Count

using System;

using System.Collections;
using System.Runtime.InteropServices;

namespace CoolectiionHastable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();


            ht.Add("Id", 1123);              
            ht.Add("Name", "Sumit");
            ht.Add("Salary", 25000.00);
            ht.Add("Designation", "Manager");
            ht.Add("IsMarrid", false);

            Console.WriteLine(ht.Count) // this method count how many key

            Console.ReadLine();
        }
    }
}

/* output
5       
*/

STACK Non-Generic Collection:-

All non-generic collection classes have these features.

  1. They can store homogeneous elements as well as heterogeneous elements.

  2. They are not type safe. (you can put the data defrent defren data type)

  3. It can automatically resize dynamically (Auto Resizing).

Stack means pile of object (means like kitabo ka dher laga de means ke ke uper ek)

Push and pop

using System;
using System.Collections;     // it improtant name space



namespace StackDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Last in first out
            Stack mystack=new Stack();
            mystack.Push("Sumit");  // you can store diffrent defrent type data
            mystack.Push(27);
            mystack.Push(5.11);
            mystack.Push(false);
            mystack.Push("Gupta");

            foreach(object item in mystack)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();

        }
    }
}

C# include a special type of collection which stores element in LIFO style (LAst in First Out).

C# includes a generic and non-generic Stack.Here,you are going to learn about the non-generic stack.

Stack allows null value and also duplicate values.It provides a push() method to add a value and Pop() or Peek() methdos to retrive values.

Stack allow null and also doplicate values.

A stack is used to create a dynamic collection which grows, according to the need of your program.

The capacity of a Stack is the number of elements the Stack can hold.As element are added to a stack, the capacity is automatically incresaed as required through reallocation.

In a stack,you can store element of the same type or different type

The stack class implements the IEnumerable,ICollection and ICloneble interface

QUEUE (Nongeneric Collection) (System.collection) (FIFO) first in first out

Queue Meaning : a Line or sequence of pepole or vehicles.

Another meaning: Qataar Lagana

Enqueue(in) Dequeue(Out)

  1. They can store homogeneous elements as well as heterogeneous elements.

  2. They are not type safe.

  3. It can automatically resize dynamically

  4. It can automatically resize dynamically

  5. Queue collection allows multiple null and duplicate values.

                   //fifo first in first out
using System;
using System.Collections;   // it is important

namespace QueueEx
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Queue myQueue=new Queue();
            myQueue.Enqueue("Sumit");
            myQueue.Enqueue('S');
            myQueue.Enqueue(5);
            myQueue.Enqueue(true);
            myQueue.Enqueue(5.7);

            foreach(object item in myQueue)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

        }
    }
}

// first in first out
/* Output 
    Sumit
     S
     5
   True
   5.7

*/

C# includes a Queue collection class in the System.Collection namespace.

            // storing null value
using System;
using System.Collections;

namespace QueueEx
{
    internal class Program
    {

        static void Main(string[] args)
        {
            Queue myQueue=new Queue();
            myQueue.Enqueue("Sumit");
            myQueue.Enqueue("Sumit");  // duplicate

            myQueue.Enqueue(null);
            myQueue.Enqueue(null);  // we also store null 
            myQueue.Enqueue(5);
            myQueue.Enqueue(true);
            myQueue.Enqueue(5.7);

            foreach(object item in myQueue)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

        }
    }
}

/* output 
Sumit
Sumit        // here print duplicate value

            // here not print because null value
5
True
5.7
*/
 instance name <myQueue>.function name 
Count,Enqueue,Peek

Count:- Returns the totel count of element in the Queue.

Enqueue:- Adds an item into the queue.

Dequeue:- Removes and returns an item from the begining of the queue.

Peek:- Returns first item form the queue

Contain:- Check whether an item in the queue of not

Clear: Remove all the item

using System;
using System.Collections;

namespace QueueEx
{
    internal class Program
    {

        static void Main(string[] args)
        {
            Queue myQueue=new Queue();
            myQueue.Enqueue("Sumit");
            myQueue.Enqueue('A');
            myQueue.Enqueue(5);
            myQueue.Enqueue(true);
            myQueue.Enqueue(5.7);

            foreach(object item in myQueue)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("-----------------------");
            myQueue.Dequeue();                        //Using Dequeue(); function
            foreach(object inem in myQueue)
            {
                Console.WriteLine(inem);
            }
            Console.WriteLine("------------------------");
            myQueue.Dequeue();                              //Using Dequeue(); function
            foreach (object inem in myQueue)
            {
                Console.WriteLine(inem);
            }
            Console.ReadLine();

        }
    }
}
/* Output
Sumit
A
5
True
5.7
-----------------------
A                       //here remove first fifo means Sumit remove
5
True
5.7
------------------------
5              //here remove first fifo means Sumit and char A remove
True
5.7 */
using System;
using System.Collections;

namespace QueueEx
{
    internal class Program
    {

        static void Main(string[] args)
        {

            Queue myQueue=new Queue();
            myQueue.Enqueue("Sumit");
            myQueue.Enqueue('A');
            myQueue.Enqueue(5);
            myQueue.Enqueue(true);
            myQueue.Enqueue(5.7);

            while (myQueue.Count > 0)
            {
                Console.WriteLine(myQueue.Dequeue());

            }
            Console.WriteLine(myQueue.Count);

            Console.ReadLine();

        }
    }
}

/*output
Sumit
A
5
True
5.7
0           //  here print 0 all value is delocate

*/

DIFFERENCE BETWEEN GENERIC AND NON-GENERIC COLLECTION

Array:

  • type Saf int[]arr=new int[3];

  • Fixed Length

Non-Generic Collection

  • Not Type safe ArrayList AL=new ArrarList(3);

  • AL.Add(Object value)

  • Variable Length(Auto-Resizing)

Generic Collection:

  • Are Type Safe

  • Variable Length(Auto Resizin)

It is a type safe and auto resize

DIFEERENCE:-

NON-GENERIC COLLECTIONGENERIC COLLECTION
These are the collection that can hold elements of different data typeThese are the collection that can hold data of same data type.
It holds elements as Objects as Object type. So it includesovehead of type conversionIt reduced overehead of type- Conversions.
These are also called loosely typedThese are also called Strongly type
Not Type Safe.Type Safe.
Not SecureSecure

Generic Collection :-

  • 1. List

  • 2. Dictionary

  • 3. Stack

  • 4.Queue

LIST<T> Generic Collection

A List is one of the generic collection classes in the "System.Collection.Generic" namespace

An ArrayList resizes automatically as it grows (Auto-Resizing).

The List<T> collection is the same as an ArrayList except

that List<T> is a generic collection whereas ArrayList is a non-generic collection.

  • A List class can be used to create a collection of any type.

  • For example, we can create a list of Integers,string and even any complex type

  • List<T> class represents the list of objects which can be accessed by index

using System;
using System.Collections;
using System.Collections.Generic;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
           List<int> myNumbers=new List<int>();   // we can not store sdiffrent data in list if you want to store data diffrent
                                                 // then you create  another  object
            myNumbers.Add(11);
            myNumbers.Add(22);
            myNumbers.Add(33);
            myNumbers.Add(44);
            myNumbers.Add(55);
            foreach (int n in myNumbers)
            {
                Console.WriteLine(n);
            }
            Console.WriteLine();
            List<string> name = new List<string>();
            name.Add("Sumit");
            name.Add("Ajay");
            name.Add("Rahul");
            name.Add("Suresh");

            foreach(string s in name)
            {
                Console.WriteLine(s);
            }

            //  Console.WriteLine(myNumbers.Capacity);

            Console.ReadKey();
        }
    }
}
                //Employee Class
using System;

namespace arrayListCollection
{
    internal class Employee
    {

        public int EmpId { get; set; }
        public String Name { get; set; }

        public string desiginnation { get; set; }

    }
}

                  //Program Class
using System;
using System.Collections;
using System.Collections.Generic;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Employee emp1 = new Employee()
            {
                EmpId = 101,
                Name = "Suresh",
                desiginnation = "Maneger"
            };

            Employee emp2 = new Employee()
            {
                EmpId = 102,
                Name = "Mohan",
                desiginnation = "HR"
            };
            Employee emp3 = new Employee()
            {
                EmpId=103,
                Name="Mohan",
                desiginnation="Employee"
            };
            List<Employee> EmpList = new List<Employee>();

            EmpList.Add(emp1);
            EmpList.Add(emp2);
            EmpList.Add(emp3);

            foreach(Employee emp in EmpList)
            {
                Console.WriteLine("Employee id is :{0} Employee Name is: {1} Employee Designnation:{2}",emp.EmpId,emp.Name,emp.desiginnation);
            }

            Console.ReadKey();
        }
    }
}
/*               *Out Put* 
Employee id is :101 Employee Name is: Suresh Employee Designnation:Maneger
Employee id is :102 Employee Name is: Mohan Employee Designnation:HR
Employee id is :103 Employee Name is: Mohan Employee Designnation:Employee*/

List<T> class can accepts null as a valid value for reference type and it also allows duplicate elements

Why to use A List

  • Unlike arrays, a List can grow in size automatically in other word a list be re-size dynamically but arrays cannot.

  • List is a generic type.

  • List is a type safe.

  • The List class also provides method to search,sort and manipulate lists.

  • Capacity Gest ot sets the totel number of elements the internal data structure can hold.

  • Count Gest the number of element contained in the List<T>.

using System;
using System.Collections;
using System.Collections.Generic;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {


            List<string> name = new List<string>();
            name.Add("Sumit");
            name.Add("Ajay");
            name.Add("Rahul");
            name.Add("Suresh");
            name.Add(null);         //  it is store null value
            name.Add("Sumit");      // duplicate value  also

            foreach (string s in name)
            {
                Console.WriteLine(s);
            }

            //  Console.WriteLine(myNumbers.Capacity);

            Console.ReadKey();
        }
    }
}
  • List<T> class can accept null as a valid value for reference type and it also allows duplicate elements

  • List<T> class is not sorted by default and element are accessed by zero-based index.

Why To Use A List

  • Unlike arrays,a List can grow in size automatically in other words a list be re-sized dynamically but array cannot.

  • List is a genaric type.

  • List is type safe. //Means same typye of data

  • The List class also provides methods to search,sort and manipulate list.

  • Add() Adds an object to the ends of the List<T>.

  • AddRange() Adds The element of the specified collection to the end of the List<T>

  • Insert an element into the List<T>at the sepecified index

  • InsertRange()Inserts the elements of a collection into the List<T>at the sepcified index

  • Remove() Remove the first occurence of a specific object form the List<T>.

  • RemoveAt() Removes the element at sepcified index of the List<T>.

  • RemoveRange() Remove a range of element from the List<T>

Properties of List

  • Capacity Gets or sets the totel number of elements the initernal data structure can hold.

  • Count Gets the number of element contained in the List<T>.

  • Add() Adds an objeect to the end of the List<T>

  • AddRange() Adds the elements of the specified collection to the end of the List<T>.

  • Insert() Insert an element into the List<T> at the specified index

                //   
AddRange() Method
using System;
using System.Collections;
using System.Collections.Generic;  //Name spase

namespace arrayListCollection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> myNumbers = new List<int>();   // we can not store sdiffrent data in list if you want to store data diffrent
                                                     // then you create  another  object
            myNumbers.Add(44);
            myNumbers.Add(33);
            myNumbers.Add(11);
            myNumbers.Add(22);
            myNumbers.Add(55);

            foreach (int n in myNumbers)
            {
                Console.WriteLine(n);
            }
            Console.WriteLine();
            myNumbers.AddRange(myNumbers);               // it is store value myNumbers means out put value is 10
            Console.WriteLine("--------------------");
            foreach(int a in myNumbers)
            {
                Console.WriteLine(a);
            }



            Console.ReadKey();
        }
    }
}

/*
OutPut 
44
33
11
22
55

--------------------
44
33
11
22
55
44
33
11
22
55*/

Enum?

  • Enum is a set of Constants.

  • An enum is a special “class“ that represent a group of constants (unchangeable/read-only variables)

  • Enum is short for “enumeration“,which means”sepcifically listed”

How To Create Enum

To create a n enum, use the enum keyword (instead of or interface),and separate the enum with a comma.

using System;
namespace String2
{
    internal class PRts
    {
        enum days
        {
            sunday, //0    separated by a comma
            Monday, //1  
            Tuesday, //2
            Wednesday, //3    //it is store bydefault inteser value same array 0,1,2,
            Thursday,//4
            Friday, //5
            Satarday //6
        }
        static void Main()

In c#, an enum (or enumeration type)is used to assign constant name to a group to a group of numeric integer values.

It make constant value more readable,for example, WeekDays.Monday is more readable then number 0 when referring to the day in a week.

An enum is defined using the keyword, directly inside a namespace,class,or structure. All the constant name can be declared inside the curly brackets and separated by a comma.

  • The default underlying type of an enum is int.

  • The default value for first element is zero and incremented by 1.

  • Enums are vlue types.

  • Enum are more redable and maintable.

  • Enum is converted into abstract behind the scencs.

Enum Values

  • If Values are not assigned to enum members,then the compiler will assign integer value to each member starting with zero by default.

  • The first member of an enum will be 0,and value of each successive member is increased by 1.

IS vs AS

. 1) ‘is‘ keyword is used to check the data type of an object.

.2) ‘is keyword checks‘ whether the conversion from one object type to another boject type is compatiable or not.

  1. it returns Boolean

4 ) It return true if the conversion is compatiable, else return false

 using System;
namespace ConsoleApp3
{
    internal class Program
    {

        static void Main(string[] args)
        {
            //is vs As

            object a = 456;
            bool check = a is string; //its working like if else conditoion
            Console.WriteLine(check);
            //if(a is string)
            //{
            //    Console.WriteLine("Yes a is a string");
            //}
            //else
            //{
            //    Console.WriteLine("Nort a string");
            //}

            int b = 20;
            bool che = b is int;
            Console.WriteLine(che );
        }
    }
}

AS

in the development of the software, typecasting is a common thing in many , developer need to convert a Type into another Type and sometimes he/she may get InvalidCastException. So, to overcome such type of eeception c# provides “as” operator keyword

  • ‘as‘ is a keyword used for conversion for type to another.The type can be a reference or nullable.

  • ‘as‘ keyword check the compatiblity of one object type with another object type. In case of compatible, it wll return the value of the new object type otherwise, null will be returned.

  • If the new conversion from one type to another type fails, the oit will return a null value

using System;


namespace ConsoleApp3
{
    internal class Program
    {

        static void Main(string[] args)
        {


            object a ="Sumit";
            string str = a as string;  // it is convert object to string type 
            Console.WriteLine(str);

            object i = 123;
            string x = i as string;   // rthis time here store value null    
            Console.WriteLine(x);

            //output
            //sumit
            //blank space

        }
    }
}
  • Diffrence between is & as operator

ISAS
The ‘‘is‘‘ operator is used to check if the run -time of an object is compatiable with the given type or not whereas“as“ operator is used to perform conversion betweeen compatible reference type or nullable type.
The “is” operator is of boolean type“as“ operator is not of boolean type.
The “is “operator return true if the given object is of the same type“as“ operator return the when they are compatible with the given type.
The “is“ operator returns fales if the given object is not of the same type“as“ operator returns null if the conversion is not possible.
The “is“ operator is used for only reference,boxing , and unboxing conversion“as“ operator is used only for nullable, reference and boxing conversion