.net - Call To Ctype Failing At Runtime For Cast From Int To Generic Type?

Feb 25, 2011

I know about the existence of System.Nullable(Of T) Structure.I am trying to write a class to replace it: The Nullable(Of T) Class [VB code below]. But when I tested the Nullable(Of T) Class (See NullableOfTClassTest Class, Method Main) an exception occurs when using the CType operator to convert from System.Int32.Why does this happen at runtime, why isn't my Ctype operator method being called?

NOTE: code below reordered and reduced in order to hilite problem.

Namespace MyNamespace
Public NotInheritable Class NullableOfTClassTest
Private Sub New()
End Sub

[Code]...

View 2 Replies


ADVERTISEMENT

.net - Cast To Generic Type At Runtime?

Sep 9, 2010

I'm in the process of creating a function which reflects over the properties in a class and adds them to this data structure I have. Some of the properties are generic types.So say we have DataType(Of T) that has a .Value property of type T:

Dim properties = GetType(MyType).GetFields(Reflection.BindingFlags.Public Or _
Reflection.BindingFlags.Instance)
For Each prop As fieldinfo In properties
Collection.Add(prop.Name,prop.GetValue(poco))
Next

In the collection.Add for primitive types (Integer, String, etc....) I just want to add the type... but in the case of generic I want to add the DataType(Of T).Value. I hope there is some work-around but I don't think there is a way because the type of T can not be determined at compile time right? Ideally DirectCast(prop.getvalue(poco), DataType(Of T)).Value would be possible. This is when you hoped even more dynamics appear than whats in .NET 4.0.

View 2 Replies

Unable To Cast Object Of Type .objectquery To Type Generic.list

Sep 12, 2011

I have a question about ASP.Net, visual basic I have 2 LINQ query's, the first one works, the second one doesnt, produces a

"Unable to cast object of type 'System.Data.Objects.ObjectQuery'1[SelmaV2.Products]' to type 'System.Collections.Generic.List'1[System.String]'.

[Code]....

View 1 Replies

Cast Value Type To Nullable Enumeration Type In Generic Object If All Types Are Unknown At Write-time?

Dec 14, 2011

I have a generic Class I'm using to hold information loaded from a database.I have a method which takes a DataRow as an argument, uses the object's known column name and extracts the data from the DataRow, such that:Dim loadData As T = CType(myDataRow("myColumnName"), T))works as my default assignment in most cases.Unfortunately, due to some horrifying design constraints, some of my columns may be null, and may also be taken from enumerations.This means that when <T> is Nullable(Of SomeEnumeration) the above code does not work because I can't cast 0 directly to SomeEnumeration.Zero.Is there some way to check whether <T> is Nullable(Of [Enum])? Or some way to write a method which allows Integers to be cast to Nullable(Of [Enum])?I feel like I'm forgetting something that would allow me to write one of the other of these, but my weak google-fu is turning up nothing.

EDIT: Okay, thanks to dasblinkenlight's answer below, I can detect when this circumstance is occurring, but what I need to do now is to take a type <T> which I know is Nullable(Of SomeClass), get a type reference to SomeClass and then create a new object of type Nullable(Of SomeClass) and assign that to LoadData.My problem was that I had a lot of difficulty in finding any function which would accept baseType as an actual Type.Parse accepted baseType as a parameter, I knew baseType was an [Enum] type because of dasblinkenlight's code, so I was, in this instance, able to code a solution. It's a solution which is very specific to my problem (i.e., T is Nullable(of SomeEnumeration)), but it's a solution nonetheless.

View 2 Replies

.net - Determining A Generic Type At Runtime In Non-Generic Class

Aug 14, 2010

I have a Journal that records entries for different types: Journal(Of ParentT)

[Code]....

View 2 Replies

Unable To Cast Object Of Type 'System.Collections.Generic.List`1[System.Int32]' To Type 'crmWebService.ArrayOfInt'?

May 14, 2012

I'm getting an error after sending a list to a web service.This is the code that is calling the web service:

Dim sProgramInterest As New List(Of Integer)
crmService.InsertProspectGetId(sProgramInterest.ToList)
But I'm getting this error.

[code].....

View 3 Replies

Unable To Cast Object Of Type 'ImagesFlag' To Type 'System.Collections.Generic.IEnumerable`1[ImagesFlag]'

Jan 7, 2012

And here is the code that produces the error

CODE:

How can i cast this one?

View 1 Replies

Cast An Object To A Type Extracted At Runtime?

Jan 25, 2012

I am using reflection to get an object's type, or for this issue an object that has instance properties type, at runtime and then I need to change an existing variable's type into that newly found type. Is this possible? For example, the following code does not work in the line indicated within:

Public Sub DoSomething(x As T, y As T, exp As String)
'This is a instance property on the object of a different type
'i.e. 'T.AnotherType' We need to reflect to find out what type of object

[code].....

View 1 Replies

Invalid Cast Exception Was Unhandled - Unable To Cast Object Of Type 'System.String' To Type 'System.Windows.Forms.TextBox'

Feb 9, 2012

Private
Sub cmdExit_Click(ByVal
sender As System.Object,
ByVal e

[code]....

View 3 Replies

.net - Filter Custom Dictionary With LINQ ToDictionary - "Unable To Cast Object Of Type 'System.Collections.Generic.Dictionary`2"

Jul 7, 2010

I have created a Dictionary class (MyDictionary for the example). I am currently trying to pass MyDictionary into a function, filter it into a new instance of MyDictionary and pass this new instance into another method. When I am attempting to create the second instance from the filtered first instance of MyDictionary via Lambda Expressions and the ToDictionary Method, I am getting the following error:

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'MyDictionary'. I have simplified the example and recreated it in LINQPad and am getting the same error.

Here's the simplified version of my code:

[Code]...

View 2 Replies

Converting Boolean And Date From Generic - Designer Does Not Accept A Simple CType?

Dec 6, 2010

I am creating a 'generic input dialog': InputDialog(Of T).The idea is that I can create new instances of this dialog for different values of T. For example,I can create an InputDialog(Of String) and it displays a textbox.I create an InputDialog(Of Boolean) and it displays two radiobuttons (I could use a Checkbox, irrelevant).I create an InputDialog(Of Date) and it shows a DateTimePicker.

I do this by simply checking the type of T at run-time.In this way it is not really generic, as the dialog still has to know which type T is (which is usually not the case), but the generic is in the fact that the T can be multiple types that require a TextBox. For example, InputDialog(Of String), (Of Integer), (Of Single), (Of Double), etc, all simply display a TextBox (and it is validated later),so I still want to use generics as much as possible.Anyway, the result of the dialog is of course a property of type T. This property needs to return the value in the textbox, converted from string to T, OR the value in the DateTimePicker, converted from Date to T,OR the checked property of the 'Yes' radiobutton, converted from Boolean to T.In order to convert from any object to T I googled and found this

vb.net

Imports System.ComponentModel Public Class GenericTypeConverter Public Shared Function FromObject(Of T)(ByVal value As Object) As T Dim tc As TypeConverter = TypeDescriptor.GetConverter(GetType(T)) Return CType(tc.ConvertFrom(value), T) End Function End Class

I have to use this, I cannot simply CType a string to T since a String cannot be converted to any type T.So, my Result property looks like this at the moment:

vb.net

Public ReadOnly Property Result()[code].....

This actually works for Strings, Integers, Doubles, Singles, etc. I pass it the String in the textbox and it converts it to 'T'(note: T is then a String, Integer or Double!) just fine.So, it can convert a String to a String, Integer or Double without any problems (I am validating the text before using the Result property so it will always be a valid integer, double, etc).However, it does not work for a Boolean, nor for a DateTime. When I try that, it says "BooleanConverter cannot convert from System.Boolean" or "DateTimeConverter cannot convert from DateTime". I realize it is a bit of a strange thing, since the object already IS a Boolean or a Date(Time) so no conversion should be done at all, but this doesn't work in design-time because I need to return the objects as type T.I know that T will be Boolean when the value to be converted is a Boolean, and that T will be DateTime when the value to be converted is a DateTime, but the designer does not accept a simple CType. As I said, it does not accept this:

Return CType(rbYes.Checked, T)
because 'Boolean cannot be converted to T'.

However, I did find a way to make it work, but it seems like a complete hack... I can assign the boolean to an Object and then convert that using CType:

Dim obj As Object
obj = rbYes.Checked
Return CType(obj, T)

This works, it's accepted during design-time, and it works during run-time, but it seems very wrong... Is there no better way to handle this?

View 5 Replies

Convert Class Runtime In CType In Second Parameter?

Mar 22, 2010

1. I have three classes. Now I want to know how do I convert object to my class runtime?

for example,
Dim obj as New Object
obj = CType( MyPassedObject, Class1 )

Now, in above code, MyPassedObject can be Class1 or Class2 or Class3 but it is passed as Object. So is there any way that I can convert into CType as per the type of that object, directly to that class? I mean, I can pass object name into parameter and write down CASE statement here to convert to that class but I do not want to write down Case statement for each of my class, so just want to know is it possible anyway?

I mean just for example, Can I do something like obj = CType( MyPassedObject, GetObject('Class1') or any other way?

2. Now for this obj, I am getting properties runtime and setting values and then updating.

for example,

Dim PropertyInfo As Reflection.PropertyInfo() = obj.GetType.GetProperties()

Now, Will it work fine if obj has been declared as Object and then I typeCast it runtime and then I get properties and set its values. Will it work if obj's variable type is Object or it must be that class type itself.

View 3 Replies

.net - Can A Generic Version Of A Derived Class Override A Base Method Using The Generic Type

Apr 13, 2012

Consider:

Public MustInherit Class Column
Public ReadOnly Property ReturnSomethingUseful() As Object
Get
'return something useful

[code]....

But this gives the following error:

Public Overrides Function ParseValue(sValue As String) As Boolean'
cannot override 'Public Overridable Function ParseValue(sValue As String) As Object'
because they differ by their return types.

I accept that you can't do this, but I'd like to be able to preserve the semantics of what I'm. trying to do, which is to have an untyped version that deals with Object, but a typed version in derived classes that knows about the specific type T.

View 2 Replies

Generic List Class Cast?

Jun 10, 2010

how Inheriting List(of T) should work.It seems like what I have below should work but at runtime I get the error:[code..]

If I want to cast a List(of x) to the class xlist, how should I do that?[code...]

View 15 Replies

.net - CType And Type Casting Exception

Feb 25, 2011

[Code]...

What happens when a user wants to alocate "" as Item(DurationColumn) to integer? I get an exception. clean solution to avoid this and set 0 for ""?

View 5 Replies

.net - Creating A Generic List Of A Generic Type

Jun 30, 2011

I am trying to create a list of a generic type in vb.net 2.0 framework.
This is the generic type definition:

Public Class GenericParamMap(Of T)
Public Sub New(ByVal pParamName As String, ByVal pPropValue As T)
mParamName = pParamName

[Code]....

The compiler does not allow a "T" in the method's parameter because it's not defined, but I'm not sure how or where to define it. I thought it was okay to have a generic method definition.

View 2 Replies

Generic Cannot Instantiate Instance Of The Generic Type With New?

Feb 8, 2012

I am trying to write a generic method, to avoid code duplication, which will create or activate a Form as an MDI children, based on its type. But I have to lines in error (see comments).

[Code]...

View 4 Replies

Setting Nullable Type With IF Operator Failing?

May 27, 2009

Why does this give variable A the value of zero (instead of setting it to nothing)?Dim A as double? A=If(2<3, Nothing, 6)

View 11 Replies

.net - Strongly Cast A Reflection .GetValue() Object To A Generic DbSet?

Apr 10, 2012

I'm using EF 4.3.1 in VS 2010 (.Net 4.0) to load a number of reference tables from a database in order to bind them to controls in a WinForms app.At form load, I'm pre-fetching the data so that it's stored locally, and I'm creating a dictionary of BindingSource objects that I can use to bind the local data to the controls.The intent is to minimize the impact of the EF's self validation on a cold query in order to load forms faster and improve UI responsiveness.I've written code to create and fetch the BindingSource object for a given DbSet collection as follows:

Private _dictBindings As New Dictionary(Of String, BindingSource)
Private Sub ValidateBinding(Of T As Class)(ByRef DbCollection As DbSet(Of T))
Dim strClassName As String = DbCollection.[GetType]().GetGenericArguments(0).Name
If Not _dictBindings.ContainsKey(strClassName) Then[code].....

However, I'd like to call ValidateBinding on all DbSet collections in the Model on startup, and I'd like to use reflection to iterate through the available collections in the context because we're currently loading 66 tables and could add more later.I've written the following code:

For Each propSet As PropertyInfo In Db.GetType.GetProperties(BindingFlags.Instance Or BindingFlags.Public).Where(Function(P) P.PropertyType.IsGenericType)
ValidateBinding(propSet.GetValue(Db, Nothing))
Next

but it won't work as propSet.GetValue() returns an Object instead of DbSet(of T).I also can't cast the object to a DbSet of the appropriate type, even though I know the type through reflection.I don't have access to the C# Dynamic type,and I know it's a pain to mix generics with reflection, but is there a solution for which I can pass in a reflected DbSet to my functions?Perhaps something using Method.Invoke?

View 1 Replies

VS 2008 CType Using A Variable To Hold The Type Doesn't Work

Nov 14, 2010

So I do not know at design time if the var ms is going to be a stringreader or a memorystream. So I am trying to do basically this:

Dim ms as object = myfunction...
Dim mytype As Type = ms.GetType
Dim returnedobject = ser.Deserialize(CType(ms, mytype))

But I get an error saying "type mytype is not defined". How can I do this?

View 2 Replies

Asp.net - Unable To Cast Object Of Type 'ASP.webform1_aspx' To Type 'System.Web.UI.WebControls.Button'

Jan 28, 2012

when view in browser, i got this error: Unable to cast object of type 'ASP.webform1_aspx' to type 'System.Web.UI.WebControls.Button'.

how should i solve this problem?

Line 7: If Not Page.IsPostBack Then
Line 8: Dim rowIndex As Integer = 0
<b>Line 9: Dim btn As Button = DirectCast(sender, Button)</b>

[Code].....

View 2 Replies

Unable To Cast Object Of Type 'ADODB.InternalField' To Type 'System.String

Apr 19, 2010

I had write code (just for learning), the codes :

dim Temp as string
Temp = Recordset("
Table_Field")

but, when I start Debugging the error messages "Unable to cast object of type 'ADODB.InternalField' to type 'System.String"

View 2 Replies

Unable To Cast Object Of Type 'IMAPI2FS.FsiStreamClass' To Type 'IMAPI2.IStream'

Apr 13, 2011

I am implementing IMAPI2 into my vb.net project but ran into a wall. I am getting the message Unable to cast object of type 'IMAPI2FS.FsiStreamClass' to type 'IMAPI2.IStream' when trying to start the burn. I googled around and found this is something that microsoft hasn't fixed.. which basically renders IMAPI2 useless in vb.net.

I found a post on codeproject.com by eric hadden who combined the IMAPI2.dll and IMAPI2fs.dll into an c# interop file. I also see the IBURN interop in microsoft SDK samples. I'd like to use either, but it's in c# and I'm using vb express. Does anyone know a way to get the interop into visual basic or a way around "Unable to cast object of type 'IMAPI2FS.FsiStreamClass' to type 'IMAPI2.IStream'"?

View 1 Replies

Unable To Cast Object Of Type 'System.IO.FileStream' To Type 'Excel.Application'

Jun 1, 2009

I'm having a problem with converting from one source type to a destination type. I have a form with 2 buttons (button 2 uses the OpenFileDialog to have the user open an excel file set to NewFile),(button 1 takes the contents from specific cells in NewFile and arranges them how I need into oXLApp1).

The error I get is "Unable to cast object of type 'System.IO.FileStream' to type 'Excel.Application'." in line 14 of the code below.

Public Class Form1
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

[Code]....

View 4 Replies

Unable To Cast Object Of Type 'System.String' To Type 'ADODB.Connection'

Mar 19, 2009

I'm new to VB 2005, the code below is actualy coded from VB 6 and just converted it to VB 2005. I'm having trouble with line that's on bold letters.In VB 6 this works just ok. By the way the error message is "Unable to cast object of type 'System.String' to type 'ADODB.Connection'." [code]

View 5 Replies

Error : Unable To Cast Object Of Type 'ClassA' To Type 'ClassB'

May 24, 2011

I can't cast my objects. I get: "Unable to cast object of type 'ClassA' to type 'ClassB'".

The service Class:

Public Class svc_Insp
Implements Isvc_Insp
Public Function Test(ByVal pm_income As ClassC) As String Implements Isvc_Insp.Test

[code]....

View 1 Replies

System.InvalidCastException: Cast From Type 'DBNull' To Type 'Integer' Is Not Valid?

Mar 8, 2009

Could anyone assist me in solving my problem ? My code was written in VB (VS 2003.)I got this error: System.InvalidCastException: Cast from type 'DBNull' to type 'Integer' is not valid. in my code.Here is the code line where I am getting the error: LeadCampusID = CInt(.Item("mkCampusID"))I fixed the error by making the changes in the code as :

If Not IsDBNull(.Item("mkCampusID")) Then
LeadCampusID = CInt(.Item("mkCampusID"))
Else

[code].....

View 1 Replies

Unable To Cast COM Object Of Type 'System.__ComObject' To Class Type?

May 14, 2009

Unable to cast COM object of type 'System.__ComObject' to class type 'rjsDocMan.Folder'.Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.The code where it is flagging the error is:

<div style="color: Black; background-color: White;">
treeview += AddChildren(Session("DocMan").RootFolder)
</div>

[code].....

View 4 Replies

Unable To Cast Object Of Type 'SZArrayEnumerator' To Type 'WindowsApplication1.myEnumerator'

Dec 18, 2009

I saw this thread and I had simple answer in mind. To use custom enumerator class. So I was trying to make one for that guy, which would have one more property to check whether its has reached end or not. It would also provide current position.I'm getting an error "Unable to cast object of type 'SZArrayEnumerator' to type 'WindowsApplication1.myEnumerator'." at the line 6 [see below].However, return type of values.getEnumerator says its IEnumerator. [code]

View 14 Replies

Unable To Cast Object Of Type X To Type X On Setting DataSource To A Table?

Feb 19, 2012

Columns 0 & 1 are filled from a DataAdapter from Access Database and three are added. I had this working, but I changed it to check for the column "Feed" so I could add several Locations. At first this worked,but I did someething in perfecting it and it now fails after filling the first row of the datagridview (dgvFdMed).I ran a check and the table LotsTab has 8 rows filled. Column 1 & 2 are strings and the database appears they are fine. The added columns have just been created with no value. My plan is to enter the values and then use the data from the grid.

Private Sub sfillGrid(ByVal Loc As String)
Dim i As Integer
Dim column As DataGridViewColumn

[code]....

View 12 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved