Hi
All,
C# allows you
to declare user defined conversions on classes or structs so that classes
or structs can be converted to the other type easily. Conversions can be
declared either as implicit, which occur automatically when required using the
"implicit" keyword, or they occur explicitly using the "explicit" key word which
require an explicit casting (i.e. type
casting) of the object.
All methods which define conversions must be
static.
Check out this example :
1. Create a
console application.
2. Add this code given below.
3. Checkout the conversion functions i.e. the
conversions of
MyNameclass to int and
string.
4. Currently the conversion to string and int is
"implicit" and hence we have not typed casted the conversion
of MyNameclass to string and int in the
Main.
5. Compile the program and check the output.The out
put should be "Namratha H Shah" and "13".
Code :
public class MyNameclass
{
private string FirstName
=null;
private string Initial
=null;
private string LastName
=null;
public MyNameclass()
{
FirstName ="Namratha";
Initial ="H";
LastName
="Shah";
}
static public implicit operator
string(MyNameclass o)
{
return o.FirstName + " " +
o.Initial + " " + o.LastName;
}
static public implicit operator
int(MyNameclass o)
{
return o.FirstName.Length +
o.Initial.Length + o.LastName.Length;
}
public static void Main()
{
string s = new
MyNameclass();
int i = new
MyNameclass();
Console.WriteLine(s);
Console.WriteLine(i);
Console.ReadLine();
}
}
6. Replace the
implicit keyword with explicit and then
compile ... the program will not compile unless you explicitly type
cast as follows
:
string s = (string) new
MyNameclass();
int i = (int) new
MyNameclass();
7.Make the changes and recompile and execute the
program.