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

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"/> …

JasperReports - Configuration Reference

Spring - Operations with jdbcTemplate

This class manages all the database communication and exception handling using a java.sql.Connection that is obtained from the provided DataSource. JdbcTemplate is a stateless and threadsafe class and you can safely instantiate a single instance to be used for each DAO.


Use of Callback Methods
JdbcTemplate is based on a template style of programming common to many other parts of Spring. Some method calls are handled entirely by the JdbcTemplate, while others require the calling class to provide callback methods that contain the implementation for parts of the JDBC workflow. This is another form of Inversion of Control. Your application code hands over the responsibility of managing the database access to the template class. The template class in turn calls back to your application code when it needs some detail processing filled in. These callback methods are allowed to throw a java.sql.SQLException, since the framework will be able to catch this exception and use its built-in excepti…