18 September 2007

Widening vs Narrowing

In .NET environment we have two ways for converting from one value type to our custom type. The first way is widening (implicit), by this conversions we don't lose precision i.e.

Int16 i16 = 0;

Int32 i32 = 100;

i32 = i16;


The second one is Narrowing (explicit) where is possible to lose some precision i.e.

Int16 i16 = 0;

Int32 i32 = 100;

i16 = (Int16)i32;



Below I will show you how to extend our type of explicit and implicit conversion.

class TestClass

{

public int ValueA;

public TestClass()

{

this.ValueA = 0;

}

public static explicit operator int(TestClass arg)

{

return arg.ValueA;

}

public static implicit operator TestClass(int arg)

{

TestClass t = new TestClass();

t.ValueA = arg;

return t;

}

}

Labels:

0 Comments:

Post a Comment

<< Home