Implicit type conversion: Difference between revisions

Content added Content deleted
(Added Perl example)
(Added C#)
Line 186: Line 186:
<pre>
<pre>
49.000000 was increasingly cast from 12 from 8 from 4 from 2 from 1 bytes from '1'
49.000000 was increasingly cast from 12 from 8 from 4 from 2 from 1 bytes from '1'
</pre>

=={{header|C sharp}}==
C# has built-in implicit conversions for primitive numerical types. Any value can be implicitly converted to a value of a larger type. Many non-primitive types also have implicit conversion operators defined, for instance the '''BigInteger''' and '''Complex''' types.
<lang csharp>byte aByte = 2;
short aShort = aByte;
int anInt = aShort;
long aLong = anInt;

float aFloat = 1.2f;
double aDouble = aFloat;

BigInteger b = 5;
Complex c = 2.5; // 2.5 + 0i
</lang>
Users are able to define implicit (and also explicit) conversion operators. To define a conversion from A to B, the operator must be defined inside either type A or type B. Therefore, we cannot define a conversion from '''char''' to an array of '''char'''.
<lang csharp>public class Person
{
//Define an implicit conversion from string to Person
public static implicit operator Person(string name) => new Person { Name = name };

public string Name { get; set; }
public override string ToString() => $"Name={Name}";

public static void Main() {
Person p = "Mike";
Console.WriteLine(p);
}
}</lang>
{{out}}
<pre>
Name=Mike
</pre>
</pre>