Skip to main content

Type Conversion

This is always a hard topic for myself. So, it's a good opportunity here for myself to understand well about how this work in C# or .net world.

Instead of one-to-one mapping of bits from one variable into another, you need to use type conversion on the data. Type conversion takes two forms:
Implicit conversion: Conversion from type A to type B is possible in all circumstances, and the rules for performing the conversion are simple enough for you to trust in the compiler. Implicit conversion requires no work on your part and no additional code.

Explicit conversion: Conversion from type A to type B is possible only in certain circumstances or where the rules for conversion are complicated enough to merit additional processing of some kind.

Implicit conversions
Consider the code shown here: var1 =var2; This assignment may involve an implicit conversion if the type of var2 can be implicitly converted into the type of var1, but it could just as easily involve two variables with the same type, in which case no implicit conversion is necessary.

Note: bool and string have no implicit conversions.

If you try to fit a value into a variable but that value is outside the range of values the variable can take, then there will be a problem. For example, a short type variable is capable of storing values up to 32767, and the maximum value allowed into a byte is 255, so there could be problems if you try to convert a short value into a byte value. If the short holds a value between 256 and 32767, then it simply won't fit into a byte.

If you know that the value in your short type variable is less than 255, then you should be able to convert the value, right? The simple answer is that, of course, you can. The slightly more complex answer is that, of course, you can, but you must use an explicit conversion. Performing an explicit conversion is a bit like saying "OK, I know you've warned me about doing this, but I'll take responsibility for what happens."

Explicit Conversions
As the name suggests, an explicit conversion occurs when you explicitly ask the compiler to convert a value from one data type to another. These conversion require extra code, and the format of this code may vary, depending on the exact conversion method.


For example, the following modification to the code from the last section attempts to convert a short
value into a byte:
byte destinationVar;
short sourceVar = 7;
destinationVar = sourceVar;
Console.WriteLine("sourceVar val: {0}", sourceVar);
Console.WriteLine("destinationVar val: {0}", destinationVar);

If you attempt to compile the preceding code, you will receive the following error:
Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists(are you missing a cast?)

To get this code to compile, you need to add the code to perform an explicit conversion. The easiest to do that in this context is to cast the short variable into a byte, as below,
destinationVar = (byte)sourceVar;




What happens when you try to force a value into a variable into which it won’t fit? Modifying your
code as follows illustrates this:
byte destinationVar;
short sourceVar = 281;


destinationVar = (byte)sourceVar;
Console.WriteLine("sourceVar val: {0}", sourceVar);
Console.WriteLine("destinationVar val: {0}", destinationVar);
This results in the following:
sourceVar val: 281
destinationVar val: 25


What happened? Well, look at the binary representations of these two numbers, along with the maximum

value that can be stored in a byte, which is 255:
281 = 100011001
25 = 000011001
255 = 011111111



You can see that the leftmost bit of the source data has been lost. This immediately raises
a question: How can you tell when this happens? Obviously, there will be times
when you will need to explicitly cast one type into another, and it would be nice to know
if any data has been lost along the way. Not detecting this could cause serious errors — for
example, in an accounting application or an application determining the trajectory of a
rocket to the moon



Two keywords exist for setting what is called the overflow checking context for an expression: checked
and unchecked. You use these in the following way:
checked(<expression>)
unchecked(<expression>)
You can force overflow checking in the last example:
byte destinationVar;
short sourceVar = 281;
destinationVar = checked((byte)sourceVar);
Console.WriteLine("sourceVar val: {0}", sourceVar);
Console.WriteLine("destinationVar val: {0}", destinationVar);

When this code is executed, it will crash with the error message as before (this was compiled
in a project called OverflowCheck).
However, if you replace checked with unchecked in this code, you get the result shown earlier, and no
error occurs. That is identical to the default behavior, also shown earlier.
You also can configure your application to behave as if every expression of this type includes the
checked keyword, unless that expression explicitly uses the unchecked keyword (in other words,
you can change the default setting for overflow checking). To do this, you modify the properties
for your project by right-clicking on it in the Solution Explorer window and selecting the Properties
option.


number.
You can specify many such explicit conversions in this way, as the following table shows:

Convert.ToBoolean(val) : result val converted to bool
Convert.ToByte(val): val converted to byte
....


Comments

Popular posts from this blog

Quicksort implementation by using Java

 source: http://www.algolist.net/Algorithms/Sorting/Quicksort. The divide-and-conquer strategy is used in quicksort. Below the recursion step is described: 1st: Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value(e.g. some people would like to pick the first element and do the exchange in the end) 2nd: Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Apply quicksort algorithm recursively to the left and the right parts - the previous pivot element excluded! Partition algorithm in detail: There are two indices i and j and at the very beginning of the partition algorithm i points to the first element in the array and j points to the last one. Then algorithm moves i forward, until an element with value greater or equal

Live - solving the jasper report out of memory and high cpu usage problems

I still can not find the solution. So I summary all the things and tell my boss about it. If any one knows the solution, please let me know. Symptom: 1.        The JVM became Out of memory when creating big consumption report 2.        Those JRTemplateElement-instances is still there occupied even if I logged out the system Reason:         1. There is a large number of JRTemplateElement-instances cached in the memory 2.     The clearobjects() method in ReportThread class has not been triggered when logging out Action I tried:      About the Virtualizer: 1.     Replacing the JRSwapFileVirtualizer with JRFileVirtualizer 2.     Not use any FileVirtualizer for cache the report in the hard disk Result: The japserreport still creating the a large number of JRTemplateElement-instances in the memory        About the work around below,      I tried: item 3(in below work around list) – result: it helps to reduce  the size of the JRTemplateElement Object        

Stretch a row if data overflows in jasper reports

It is very common that some columns of the report need to stretch to show all the content in that column. But  if you just specify the property " stretch with overflow' to that column(we called text field in jasper report world) , it will just stretch that column and won't change other columns, so the row could be ridiculous. Haven't find the solution from internet yet. So I just review the properties in iReport one by one and find two useful properties(the bold  highlighted in example below) which resolve the problems.   example: <band height="20" splitType="Stretch" > <textField isStretchWithOverflow="true" pattern="" isBlankWhenNull="true"> <reportElement stretchType="RelativeToTallestObject" mode="Opaque" x="192" y="0" width="183" height="20"/> <box leftPadding="2"> <pen lineWidth="0.25"/>