Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB vs C# — CType vs ChangeType

Tags:

c#

.net

vb.net

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...

like image 341
jamheadart Avatar asked May 01 '18 07:05

jamheadart


People also ask

Is Visual Basic based on C?

Visual Basic can also be used within other Microsoft software to program small routines. Visual Basic was succeeded in 2002 by Visual Basic . NET, a vastly different language based on C#, a language with similarities to C++.

Which is better VB or C#?

Even though there is less prominence of VB.NET community, but still we can say VB.NET is better than C#. 1. VB.NET uses implicit casting and makes it easier to code whereas in C# there are lot of casting and conversions needs to be done for the same lines of code.

Is VB same as C++?

The main difference between Visual Basic and Visual C++ is that Visual Basic is an Object Oriented Programming Language while Visual C++ is an Integrated Development Environment (IDE). Visual Basic is a user-friendly programming language developed by Microsoft.


1 Answers

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));
like image 162
Sweeper Avatar answered Sep 22 '22 18:09

Sweeper