Set - 2

Question 21 :

How do you convert a value-type to a reference-type? 

Answer :

Use Boxing.


Question 22 :

What happens in memory when you Box and Unbox a value-type?

Answer :

Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.Difference between directcast and ctype. 

Answer1
DirectCast requires the run-time type of an object variable to bethe same as the specified type.The run-time performance ofDirectCast is better than that of CType, if the specified type and the run-time typeof the expression are the same. Ctype works fine if there is a valid conversion defined between the expression and the type. 

Answer2
The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. 

An example of a ctype and directcast. 

In the preceding example, the run-time type of Q is Double. CType succeeds because Double can be converted to Integer, but DirectCast fails because the run-time type of Q is not already Integer


Question 23 :

ctype(123.34,integer) - should it throw an error? Why or why not?

Answer :

Answer1
It would work fine. As the runtime type of 123.34 would be double, and Double can be converted to Integer. 

Answer2
the ctype(123.34,integer) will work fine no errors


Question 24 :

directcast(123.34,integer) - should it throw an error? Why or why not?

Answer :

It would throw an InvalidCast exception as the runtime type of 123.34 (double) doesnt match with Integer.


Question 25 :

Difference between a sub and a function.

Answer :

Answer1
A Sub does not return anything whereas a Function returns something. 

Answer2
-A Sub Procedure is a method will not return a value
-A sub procedure will be defined with a "Sub" keyword

Sub ShowName(ByVal myName As String)
Console.WriteLine("My name is: " & myName)
End Sub

-A function is a method that will return value(s).
-A function will be defined with a "Function" keyword

Function FindSum(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Dim sum As Integer = num1 + num2
Return sum
End Function