MCTS Examen 70-536 – Converting Types
Hello everyone!
Today I learn about Type-Conversion and will share my notes with you. Have fun !
General
- C# allows widening conversion (destination type can accommodate all possible values) but prohibits narrowing conversion (possible loss of precision).
- Methods to Convert in C#
- System.Convert (Both Types need to implement System.IConvertible)
- (type) operator
- type.ToString / type.Parse
- type.TryParse / type.TryParseExact
Narrowing convertions may return incorrect result.
Boxing / Unboxing
- Boxing converts a value type to a reference type
- Unboxing converts a reference type to a value type
- Boxing produces overhead
- Boxing occures when:call of virtual members inherited from System.Object (ToString …)
- So you should avoid boxing by:
- Implement Overloads for methods, instead of using an object parameter
- Use Generics
- Override ToString, Equals and GetHash when defining structures
- Conversion Operators for narrowing and widening conversions
- Override ToString and Parse to provide conversion
- Implementing System.IConvertible (For System.Convert usage and curture specific conversion)
- Implementing TypeConverter to use PropertyWindows (Designtime) [Not Important for Exam]
struct MyType
{
public int TypeValue;
public static implicit operator MyType(int arg)
{
MyType ret = new MyType();
ret.TypeValue = arg;
return ret;
}
public static explicit operator int(MyType arg)
{
return arg.TypeValue;
}
}
Anything new for me ?
The part about the operators was pretty new for me. I will try to use it more often
)
I dont use structs very often, but good to know what to avoid when it comes to boxing and unboxing.


