VB vs C# — CType vs ChangeType

  • A+
Category:Languages

Why does this work in VB.Net:

Dim ClipboardStream As New StreamReader(     CType(ClipboardData.GetData(DataFormats.CommaSeparatedValue), Stream)) 

But this is throwing an error in C#:

Stream is a Type, which is not valid in the current context

ClipboardStream = new StreamReader(Convert.ChangeType(     ClipboardData.GetData(DataFormats.CommaSeparatedValue), Stream)); 

To be honest, I'm not 100% clued up on converting types, I've only ever used them in code snippets and now I'm trying to convert a simple VB code snippet to a C# version...


ChangeType accepts a Type as the second parameter, so you should write typeof(Stream). typeof(Stream) evaluates to a Type instance representing the type Stream. Just using Stream there does not work because it does not evaluate to a value. It's not an expression.

Anyway, you shouldn't be using ChangeType here anyway, you should cast, which is the C# equivalent of CType:

 ClipboardStream = new StreamReader((Stream)ClipboardData.GetData(DataFormats.CommaSeparatedValue)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: