Pages

Wednesday, 22 July 2015

User-Defined Conversions

User-Defined Conversions

Besides the standard conversions, you can also define both implicit and explicit conversions for your own classes and structs.
The syntax for user-defined conversions is shown in the following code.
public static implicit operator [Target Type] ( [Source Type] [Identifier] )
{
 ...
 return [Object Of Target Type];
}
For example, the following shows an example of the syntax of a conversion method that converts an object of type Person to an int:
public static implicit operator int(Person p)
{
 return p.Age;
}

Constraints on User-Defined Conversions

There are some important constraints on user-defined conversions. The most important are the following:
  • You can only define user-defined conversions for classes and structs.
  • You cannot redefine standard implicit or explicit conversions.
  • The following are true for source type S and target type T:
    • S and T must be different types.
    • S and T cannot be related by inheritance. That is, S cannot be derived from T, and T cannot be derived from S.
    • Neither S nor T can be an interface type or the type object.
    • The conversion operator must be a member of either S or T.
  • You cannot declare two conversions, one implicit and the other explicit, with the same source and target types.

Here's the sample of how to make user-defined conversions:
class Person
{
 public string Name;
 public int Age;
 
 public Person(string name, int age)
 {
  Name = name;
  Age = age;
 }
 
 public static implicit operator int(Person p) // Convert Person to int.
 {
  return p.Age;
 }
 
 public static implicit operator Person(int i) // Convert int to Person.
 {
  return new Person("Nemo", i); 
 }
}

class Program
{
 static void Main( )
 {
  Person bill = new Person( "bill", 25);
  int age = bill;
  Console.WriteLine("Person Info: " + bill.Name + ", " + age);
  
  Person anon = 35;
  Console.WriteLine("Person Info: " + anon.Name + ", " + anon.Age);
 }
}

The code will display following output:
Person Info: bill, 25
Person Info: Nemo, 35

If you had defined the same conversion operators as explicit rather than implicit, then you would have needed to use cast expressions to perform the conversions, as shown here:
...
 public static explicit operator int( Person p )
 {
  return p.Age;
 }
...
static void Main( )
{
 ... 
 int age = (int) bill;  //Requires cast expression
 ...
}

0 comments:

Post a Comment