CType question

  • Thread starter Thread starter Jeff Bunting
  • Start date Start date
J

Jeff Bunting

Given the following:

Dim t As Type = Me.GetType
Dim ClassProperties As PropertyInfo() = t.GetProperties
Dim ClassProperty As PropertyInfo
Dim ClassType As System.Type

ClassProperty = t.GetProperty(PropertyName)
ClassType = ClassProperty.PropertyType

DefaultPropertyValue = CType("a", ClassType)

What is wrong with the last line? Intellisense keeps saying that type
'ClassType' is not defined.

The docs say that the typename parameter of CType can be:
"Any expression that is legal within an As clause in a Dim statement, that
is, the name of any data type, object, structure, class, or interface."

Isn't that what I have?
 
Jeff,
Isn't that what I have?

No, the type expression must be something that the compiler can
evaluate at compile time, it can't be a variable.

What are you actually trying to accomplish?



Mattias
 
I know what your trying to do here, I've tried it before. As Mattias said
the compiler must know at compile time to do type converison.

However, keep in mind that everything in the .NET framework is derived from
Object so, by returning something as an object you can put it into any
variable and the rest should be taken care of.

-CJ
 
The second param is suppose to be a type. You could do

DefaultPropertyValue = CType("a", System.Type)
 
* "Jeff Bunting said:
DefaultPropertyValue = CType("a", ClassType)

What is wrong with the last line? Intellisense keeps saying that type
'ClassType' is not defined.

The type must be known when compiling the application, not when running
it. You will have to use 'GetType(...)', for example.
 
I was trying to cast a variable whose type wouldn't necessarily be known
until run time.
Apparently I need to take a different approach to doing this; I realize
some values wouldn't be valid for all data types.
 
I guess this is just what I want then:

If ClassType Is GetType(System.String) Then DefaultPropertyValue = ""
Else If ClassType Is GetType(System.Int32) Then DefaultPropertyValue = "0"

I'm still learning this as you can tell, so was playing around to see what I
could do.

Thanks!
 
Hi Jeff,

A variable has no fixed lenght, so it can only be a reference.

A value can direct be used and has not to be referenced and needs therfore
when there is a properiate operand only one cycle (I do not know the
operandset from the 86 and either from the new planned processors).

Just my 2 eurocents

Cor
 
Back
Top