Explicit Conversion In C# Language

Introduction

 An explicit operator are  call to the cast operators. A user require to make sure that cast is valid. So the main purpose of explicit is user's define type conversion operator. In other word, a user involves casting from one type to another type through explicit conversion.

Example

using System; 

class class1 // Create class

{

    public void show() //create function

    {       

        Console.WriteLine("to Noida");

    }

 

    //Explit operator which convert of class1's type to class2 type

   public static explicit operator class2(class1 a)      

    {

        return new class2() ;

    }

}

 

class class2

{

    public void show()

    {

       

        Console.Write("Welcome ");

    }

 

    //Explit operator which convert of class2's type to class1 type

    public static explicit operator class1(class2 h)

    {

        return new class1() ;

    }

}

 

class Program

{

    static void Main()

    {

        class2 obj = new class2(); //create object of class2

 

        obj.show();   //call to class2's function

        class1 a = (class1)obj;//convert class2's object in class1 type

        a.show();  // call to class1's function

        Console.ReadLine();

             

    }

}


Output:


output.jpg