0

there are an array of options for casting in VB.NET and I wanted to clarify my understanding.

DIRECTCAST

Please see the code below:

Dim p as New PostGraduate
Dim s as student = directcast(p,student)

This is a CAST rather than a conversion. Therefore the reference changes to a Student and the value is still a PostGraduate.

cstr and ctype

Please see the code below:

dim l as long=100
dim i as integer = cstr(l)
dim j as integer = ctype(l,integer)

These are both conversions so the reference and value changes to an integer. cstr and ctype are identical. cstr and ctype call Convert.ToString, Convert.ToInt etc behind the scenes. How is a custom object e.g. Student converted (Object.ToString?)

DataReader.getString (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getstring%28v=vs.110%29.aspx) and DataReader.getOrdinal (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal%28v=vs.110%29.aspx)

When should these be used? Do they call convert.ToString behind the scenes?

I am confused why there are so many different ways to do the same thing.

w0051977
  • 15,099
  • 32
  • 152
  • 329
  • The question is based on a nonsensical example. No DirectCast is required and no conversion is needed. Option Strict On does not require you to write code like this. You'll have to come up with a real problem. – Hans Passant Jun 29 '14 at 09:20
  • @hans passant, i have removed all references to option strict. Is the question ok now? – w0051977 Jun 29 '14 at 09:36
  • 1
    possible duplicate of [Difference between DirectCast() and CType() in VB.Net](http://stackoverflow.com/questions/3056514/difference-between-directcast-and-ctype-in-vb-net) – Bjørn-Roger Kringsjå Jun 29 '14 at 10:59
  • the first line in each link explains the difference. .GetString returns the **string value** of column; .GetOrdinal returns the **integer ordinal** of a column, two very different things both in data type and data meaning. This line fails under Option Strict: `dim i as integer = cstr(l)`. Neither i nor j needs to involve strings at all except that your code uses CSr to convert a long to integer; neither calls Convert.ToInt, `i` uses an internal VB `ToInteger` function (or `ToString` to handle the `CInt(Cstr(long))` code). Your `j = CType(l` gets optimized out and becomes a checked cast. – Ňɏssa Pøngjǣrdenlarp Jun 29 '14 at 13:00

0 Answers0