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.
For example, the following shows an example of the syntax of a conversion method that converts an object of type
Here's the sample of how to make user-defined conversions:
The code will display following output:
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:
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];
}
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 typeT
:S
andT
must be different types.S
andT
cannot be related by inheritance. That is,S
cannot be derived fromT
, andT
cannot be derived fromS
.- Neither
S
norT
can be an interface type or the type object. - The conversion operator must be a member of either
S
orT
.
- 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
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