Have A Static Generic Function In .net 2.0 VB Code?
Sep 2, 2009
I must be doing something wrong here (because really, what are the chances of me tripping over another bug in the Vb.net compiler?)I have a static generic function in .net 2.0 Vb code, I thought it was time to "upgrade" it to be an extension method, but the compiler complains with Extension method 'AddIfUnqiue' has type constraints that can never be satisfied.
Here's a trivial example that displays the same problem. The old static version (which works fine) followed by the extension method
Public Class MyStaticClass
Public Shared Sub AddIfUnqiue(Of T, L As {List(Of T)})(ByVal this As L, ByVal item As T)
If this.IndexOf(item) < 0 Then
[code].....
View 1 Replies
ADVERTISEMENT
Dec 30, 2009
how I can dynamically load a control inside of a shared/static function?The function itself is inside of a mustinherit/abstract class.(It's an ASP.NET project in VB) I want to do something like this:[code]I'm getting "Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.",but I don't understand this error.I understand what it means, I just don't understand why calling LoadControl isn't seen by the compiler as being an explicit instance of the class. What's not explicit about using LoadControl to create a new control from a file? I tried creating a new user control and initializing it, then setting it to a different control with LoadControl to no avail.I also don't want to do a DirectCast because I'm trying to put this in a shared, mustinheret (abstract) class, which therefore doesn't have an .aspx file to write in a <%@ Reference Control="~/SomeControlPath.ascx" %>, so the class name is unavailable.What I'm trying to do is write a static function that takes some value and returns a control based only on that control's source file location.The end result is a user-modifiable list of controls.They get a column of controls that they freely add, remove, or reorder based on a static list of available child controls that I specify.
View 4 Replies
Sep 16, 2010
Here's what I've got:
<textarea id="TextArea1" rows="6" cols="20" runat="server"></textarea>
and in the code-behind:
partial class _Default : System.Web.UI.Page
[code]....
View 4 Replies
Aug 20, 2010
I get this error: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Partial Class _Default
Inherits System.Web.UI.Page
<WebMethod()> _
[Code]....
I know it has something to do with the fact that the first function is shared and the second function should probably be Public as well but I don't fully understand the reason behind it. Probably not relevant but I'm calling the web method from some javascript.
View 1 Replies
May 31, 2011
Anyone want to try converting this to VB?
[Code]...
It is supposed to sort any type of object. Taken from here
View 1 Replies
Jun 2, 2010
Question: I want to call a generic function, defined as:
Public Shared Function DeserializeFromXML(Of T)(Optional ByRef strFileNameAndPath As String = Nothing) As T
Now when I call it, I wanted to do it with any of the variants below:
Dim x As New XMLserialization.cConfiguration
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of x)()
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(GetType(x))()
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of GetType(x))()
But it doesn't work.I find it very annoying and unreadable having to type
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of XMLserialization.cConfiguration)()
Is there a way to call a generic function by getting the type from the instance ?
View 5 Replies
Jun 7, 2012
I have a grid view with a lot of columns, all need to be sorted on. I have seen a few snippets out there, but I cannot get any of them to work with my example. Here is what I have so far.
Protected Sub gvSearch_OnSorting(ByVal sender As Object, _
ByVal e As GridViewSortEventArgs)
If Not Session("sort") Is Nothing Then
[code].....
View 1 Replies
Oct 12, 2011
written a generic "LaunchForm" function? For all the menu items I have that open a form, I would like to write one function that will launch the form as opposed to writing the same code several times.
View 2 Replies
Sep 16, 2011
I have an abstract class in VB.NET. I want all classes that inherit from this class to return whatever value makes sense. For example, it could be an Decimal, Integer, String. How can I delcare the function in the abstract base class to allow for this? Is this even possible?
[Code]...
View 2 Replies
Oct 14, 2010
I have created a couple of simple functions in VB.NET that simply return a control of a certain type that I already know, such as HtmlInputHidden, Label, etc. That means that each of the functions is created only for that special purpose. What I'd like to do is combine all those functions into one function using generics. The common things shared by each of the functions is a control Id and a control type.What I have got so far is:
Public Function GetControl(Of T)(ByVal ctrlId As String) As T
Dim ctrl As Control = Me.FindControl(ctrlId)
If (Not ctrl Is Nothing) Then
[code]....
But the line " GetControl = CType(ctrl, T)" is giving me a compile error:
Value of type 'System.Web.UI.Control' cannot be converted to 'T'
This is in .NET Framework 2.0.
View 2 Replies
Apr 1, 2009
I am attempting to create a generic function that the students in my introductory VB .NET course can use to search a single dimension array of a structure.[code]...
My question is: Is there a way to reference the individual structure fields in the array from inside the function? I was trying to make it generic so that the student could simply pass their array into the function - their structure may be named differently than mine and the field names may be different.
I suspect there are other ways to deal with this situation, but I was trying to keep it to just a simple single-dimension array of a structure. I don't think it is possible to do what I want, but I wondered what others thought.
View 5 Replies
Aug 24, 2010
I am trying to write a generic function that will check each database parameter to see if it is null, and if so, return DBNull; if not, return the object.So here is my function:
Public Shared Function CheckForNull(ByVal obj As Object) As Object
If obj <> Nothing Then Return obj Else Return DBNull.Value
End Function
[code].....
View 1 Replies
Feb 16, 2011
I can create classes that use generics, however I was wondering if it is possible to apply this to a shared method rather than rely on the caller casting to the correct type.This is the method:
Public Shared Function DeserializeObject(ByVal serializedXml As String, ByVal givenType As System.Type) As Object
Dim serializer As New XmlSerializer(givenType)
Return serializer.Deserialize(New IO.StringReader(serializedXml))
End Function
I'm pretty sure this can't be done, but thought I'd check (if so Extra points will be awarded if someone can technically explain why the compiler can't do this)..
View 3 Replies
Oct 26, 2011
My question here is, what are the negative effects of using a generic function such as this? Calling this function does work, and in a test console module, it compiles perfectly fine. I do know this is not a strongly typed function, and is %100 bad practice. But it works perfectly. The purpose of a function like this, would be to handle string input that needs to be inserted in a particular format depending on the type. I also read some other questions on this here on stackoverflow, and suggestions pointed to using (Of T) functions, and variations like that. Why not do it this way? or is there another simple way of accomplishing this without creating a whole nothing class or larger amounts of code.[code]
View 1 Replies
Jan 18, 2011
I like to turn Option Strict On I cant figure out how to write the generic version of this function?
Public
Shared
Sub UpdateItem(ByRef
oldValue As
[code]....
View 8 Replies
Apr 29, 2010
Currently I have written a function to deserialize XML as seen below.How do I change it so I don't have to replace the type every time I want to serialize another object type ? The current object type is cToolConfig. How do I make this function generic ?
Public Shared Function DeserializeFromXML(ByRef strFileNameAndPath As String) As XMLhandler.XMLserialization.cToolConfig
Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(cToolConfig))
Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8)
Dim ThisFacility As cToolConfig
[code]....
View 1 Replies
Jan 13, 2011
I would like to write a generic function that would search a List(Of T) for all elements of type TFilter and return a List(Of TFilter) which comprises those elements.
I've tried this:
Public Function FilterList(Of T, TFilter)(ByVal ListToFilter As List(Of T)) As List(Of TFilter)
Return ListToFilter.FindAll(Function(z) z.GetType.Equals(GetType(TFilter))).ConvertAll(New Converter(Of T, TFilter)(Function(z) CType(z, TFilter)))
End Function
But, it gives the following error:
Value of type 'T' cannot be converted to 'TFilter'.
View 2 Replies
Jun 4, 2012
What's the best way to handle this situation: I have this generic function
Function FieldValue(Of T)(row As DataRow,fieldName As String) As T
Return If(row.IsNull(fieldName),Nothing,CType(row(fieldName),T))
End Function
In the special case where the field value is null and T is String, I want to return String.Empty instead of Nothing.
View 1 Replies
Jun 8, 2009
I have a following code which works fine
MsgBox(AddSomething(Of String)("Hello", "World"))
Public Function AddSomething(Of T)(ByVal FirstValue As T, ByVal SecondValue As T) As String
Return FirstValue.ToString + SecondValue.ToString
[code].....
View 3 Replies
Jan 2, 2011
i've been trying to toy around with generics in vb.net in an example project. At the moment, it looks like this:
I have an interface called IRow (and a class that implements it as a Datarow).
A second interface is ICanGetByRow, which looks like this:
Public Interface ICanGetByRow(Of T)
Function GetByRow(ByVal Row As IRow) As T
End Interface
The function simply takes an IRow and converts it to T. Thats easy enough. Now, for easier access, i want to implement a function in the IRow interface which takes the row and converts it into said ICanGetByRow.
My interface was enhanced by the following function
Function GetObj(Of T As ICanGetByRow(Of T))() As T
You can probably see the problem. If i implemented it like this:
Public Function GetObj(Of T As ICanGetByRow(Of T))() As T Implements IRow.GetObj
Dim foo As New T
foo.GetByRow(Me)
Return foo
End Function
i wouldn't be allowed to construct a new T, and when i tried to make it work by telling the generic function that my interface has a constructor, he wouldn't let me invoke GetByRow anymore.
Public Function GetObj(Of T As New, ICanGetByRow)() As T Implements IRow.GetObj
Dim foo As New T
foo.GetByRow(Me)
Return foo
End Function
how to tell a generic function that it will get a ICanGetByRow(of T) which has a constructor
View 1 Replies
Feb 23, 2010
I have a generic repository that I communicate with my object context with. My object context has function imports that I want to be able to call through my generic repository. Currently I call them through an "Execute" function, but this is not ideal because I have to pass in my function name and parameters as strings which can cause run-time exceptions. My function imports map to complex types.
Is there a way to do something similar to:
Dim rep As IRepository(Of ComplexType)
Dim type As ComplexType = rep.Find(where:=Function(t) t.FunctionImport(parm, parm)).First()
Here is my generic repository as is:
[Code]...
View 1 Replies
Apr 18, 2011
Suppose I want to write a generic function that will return the fully qualified name of the data type. In other words, how would you implement the following: Public Shared Function Foo(Of T)() As String ' Return the fully qualified name of T End Function
View 1 Replies
Jan 8, 2011
In vb.net, it is possible to design a function which can operate on generic parameters which meet multiple constraints. For example, it is possible to have a function accept as a parameter a class which inherits from Control and implements IList. This function could use "Control" or "IList" methods on such an object, and also pass the object to anything that expected a Control or an IList [note that this particular combination was chosen to facilitate a brief example, not to be a particularly useful combination].
[Code]...
This approach provides compile-time type-safety; there's no need for a cast that could fail at runtime. An alternative approach would be to pass the argument as either a Control or an IList, and have the function cast to the other. That would, however, fail at runtime if the object that was passed didn't in fact meet both constraints.
Under what circumstances is it good to use a generic function like the above, in what cases would it be better to have objects which are going to meet both constraints have a new interface like IListableControl(Of T) which would include a TheControl property that would return itself (cast as a control), and in what cases would it be better to have a generic ISelf(of T) interface, any implementor of which would be expected to provide a "Self" property that would return itself as a T?
Using multi-constrained generics, it's possible to do a lot of things without requiring any run-time typecasts, but I don't know what the performance costs are likely to be. I tried writing a short program to generate 65,536 different generic types at run-time, e.g. Foo(of Bar(Of Foo(Of Foo(Of Bar(Of Foo(...(Of Blah)) and it got pretty slow, so I can tell that the time required to handle generics isn't fixed, but I don't know what factors affect it.
View 1 Replies
Jun 23, 2009
The idea is to expand on the existing, old, and lacking Inputbox, to allow for:1. A greater variety of types (Integers, doubles, List(Of String), etc.2. Data validation.For example, if the user wants the user to quickly enter an Integer, I want a custom Inputbox form to show up with a TextBox, which only allows Integer input. If he wants the user to choose from a List(Of String), I show a form with a Combobox instead, from which the user can then choose.
View 8 Replies
Jun 4, 2009
Suppose I want to write a function like the following (as usual, a trivial example for illustrative purposes):
Public Function calcSqSum(Of T)(ByVal list As IEnumerable(Of T)) As T
Dim sumSq As T
For Each item As T In list
[Code]....
As you can probably guess, this function causes an error because a generic object is not guaranteed to implement the + operator. As far as I know, though, any numerical type (Integer, Double, Decimal, etc.) will.
Is there a way to write a (quasi-)generic function that can accept any numerical type, without having to explicitly overload the function for every such type yourself?
Alternatively, I suppose an equally acceptable solution would be to somehow check if a type implements the '+' operator (or any operator generally associated with numerical types and used by the function).
View 4 Replies
Aug 4, 2010
I wrote a serializer (to Byte Array) for dictionaries that have a string key, but an object of some sort as its value.I've never implemented a generic type in a function or used a delegate before, so I'm a bit concerned about this being significantly slower than writing a serialization function for a specific type of Dictionary (Dictionary(Of String, MyClass) for example)Should this code be significantly slower due to the use of the generic type or the delegate?
[code]...
It works, and I could loop it and compare it to a more static Dictionary serializer, but I'm more concerned about when I start using this for a lot of different String/Object dictionary combinations, and it'll take me a long time to write a bunch of static dictionary serializers (that's what I'm hoping to avoid in the first place)edit: simplified intro text
View 1 Replies
Jul 21, 2011
I've got this function:
Public Shared Function GetQueryStringValue(Of T As Structure)(ByVal queryStringVariable As String) As T
Dim queryStringObject As Nullable(Of T) = Nothing
If queryStringVariable <> Nothing Then
If HttpContext.Current.Request.QueryString(queryStringVariable) IsNot Nothing Then
queryStringObject = DirectCast(HttpContext.Current.Request.QueryString(queryStringVariable), T)
End If
[Code]...
View 2 Replies
Aug 26, 2010
I am very confuse over a Raise Events example and using delegate as a function pointer: I am clear with this function pointer example program below which creates a generic sort function for sorting integer arrays without changing the main sort function.
' Returns True if need to swap
Delegate Function CompareFunc(ByVal x As Integer, _
ByVal y As Integer) _
As Boolean
Here are two alternative target methods for the delegate - one for an ascending sort and one for a descending sort:
Function SortAscending(ByVal x As Integer, ByVal y As Integer) As Boolean
If y < x Then
SortAscending = True
End If
End Function
Function SortDescending(ByVal x As Integer, _
ByVal y As Integer) As Boolean
[Code] .....
View 1 Replies
Aug 1, 2011
I wrote my own database handling code (actually, I write T4 text templating files that generate my database code for me) and part of it takes care of converting values from a database (as Objects) to the desired types.
I have been using this generic function successfully:
vb.net
Public Overridable Function ConvertType(Of T)(value As Object) As T
Try
Return If(value IsNot Nothing AndAlso value <> DBNull.Value, DirectCast(value, T), Nothing)
[Code]....
Simple enough, but it doesn't work... The return type of the function is (and must be) T, so I cannot return a Boolean because a Boolean cannot be converted to T!
Well... It can in this case, because I specifically check that T is Boolean, but the compiler doesn't know this so it doesn't allow me to return a Boolean. I cannot cast the boolean to T either.
View 8 Replies
Aug 19, 2009
I wrote my own database handling code (actually, I write T4 text templating files that generate my database code for me) and part of it takes care of converting values from a database (as Objects) to the desired types. I have been using this generic function successfully:
vb.net
Public Overridable Function ConvertType(Of T)(value As Object) As T
Try
[code].....
View 13 Replies