How To Constrain To A ValueType
Jun 22, 2011I've just spotted this thread:>> [URL] Here is a C# article on the subject:>> [URL] how to constrain to a ValueType?
I,E:
Public Class ExampleClass(Of T As System.ValueType)
End Class
I've just spotted this thread:>> [URL] Here is a C# article on the subject:>> [URL] how to constrain to a ValueType?
I,E:
Public Class ExampleClass(Of T As System.ValueType)
End Class
I accidently wrote some code today that was like this[code]...
I immediately noticed the issue, but I had already hit the run button. It compiled successfully, I ran it through to the section and it threw an exception.
You can't do this in C#, it gives a compile error "cannot convert from 'int?' to 'int'".
Is there an 'Option Explicit' type switch that I can turn on to ensure that this sort of error does not occur again?
Consider these two functions[code]...
My question is: what is the right way to accomplish this to resolve the ambiguity so that I can pass value or references types and get overload 2, but pass Functions and get overload 1? Can I constrain the types in some way to make this happen?
I am looking into generics in .NET, and was wondering about the where T : struct constraint. I understand that this allows you to restrict the type used to be a value type. My question is, without any type constraint, you can do a limited number of operations on T. Do you gain the ability to use any additional operations when you specify where T : struct, or is the only value in restricting the types you can pass in?
I guess the question I am actually asking is that if I were to write, (in a discussion about how to use generics), "Now that you have constrained the type argument to value types, you can also do _________ on/with objects of that type", Is there anything to put in that blank? I can think of things for the other constraints, but not this one.
How can I constrain the bounds of a rectangle object, which is controlled by a mouse, so it cannot be drawn outside a PictureBox? It is kindof a standard lasso control, the user can click and drag and it will draw a box from the initial click point to the mouse's current location. The starting point is at (rectX,rectY), and the box is drawn to the bottom right using rectDimX and rectDimY (to set the width and height) to see how much of a change has occurred with the mouse. Basically, its what you get with a click and drag on a Windows desktop. The issue here is that the rectangle is able to be drawn outside the PictureBox it is being drawn on, and the next part of the code attempts to reference this location, and then fails with an OutOfMemory exception. This leads me to my second question:
[Code]....
I have created a custom ValueType:
Private Structure MyValueType
Private _integerValue As Integer
Public Sub New(initValue As Integer)
[code]....
But I can't work out how I can test the value such as this:
Dim v As New MyValueType(3)
Dim x As New MyValueType(4)
[code]....
Error:Operator '=' is not defined for Types MyValueType and MyValueType
So how do I define Operators for my ValueType (I know this must be simple but I can't find an exmaple anywhere!)?Note I don't want to test If v.Equals(x)
Am I correct in believing that any object that doesn't inherit from System.ValueType must therefore by definition be a reference type?
View 4 RepliesI attempting to implement the Addemar Web Service (e-marketing system) into my VB.NET application. I've managed to get a connection and called a simple method, returning a array of field id's that is. I get into truble when I want to return the label of that particular id.Value of type '1-dimensional array of WindowsApplication1.AddemarWS.NamedValue' cannot be converted to 'WindowsApplication1.AddemarWS.NamedValue'.
[Code]....
Is there a way you can do this ? I would like to have a collection class of T that would be able to do addition, substraction on the T type. I would like to keep T generic instead of having couple collections with the same code, but different types. How would you constrain the generic T?
Example: I would like to define a Collection(of T as IDoMaths). I wouldn't like to create my own integer etc classes with named methods to do the operations, because I think it would be slower. This part of the code is actually called very often and tends to be the bottleneck in performance.
I need to this at runtime. I checked using Reflector and value types line like Int16, for example, should contain
[Code]...
EDIT: only for the example I used directly GetType(UInt16) but in real code this part is substituted by an instance of unknown-at-design-time .NET Type
fast way in VB to go from a string to a generic type T constrained to a valuetype (Of T as Structure), when I know that T will always be some number type?This is too slow for my taste:
Return DirectCast(Convert.ChangeType(myStr, GetType(T)), T)
But it seems to be the only sane method of getting from a String --> T. I've tried using Reflector to see how Convert.ChangeType works, and while I can convert from the String to a given number type via a hacked-up version of that code, I have no idea how to jam that type back into T so it can be returned.
I'll add that part of the speed penalty I'm seeing (in a timing loop) is because the return value is getting assigned to a Nullable(Of T) value. If I strongly-type my class for a specific number type (i.e., UInt16), then I can vastly increase the performance, but then the class would need to be duplicated for each numeric type that I use.
It'd almost be nice if there was converter to/from T while working on it in a generic method/class. Maybe there is and I'm oblivious to its existence?
Conclusion:Testing the three provided implementations below and my original DirectCast/ChangeType form, @peenut's approach of using a prepared delegate to fetch the Parse method from a basic type works. No error checking is done, however, so implementors need to remember to only use this with valuetypes that have a Parse method available. Or extend the below to do error checking.
All runs were done on a 32bit system running Windows Server 2003 R2 with 4GB of RAM. Each "run" is 1,000,000 executions (ops) of the method to be tested, timed with StopWatch and reported back in milliseconds.
Original DirectCast(Convert.ChangeType(myStr, GetType(T)), T):
1000000 ops: 597ms
Average of 1000000 ops over 10 runs: 472ms
Average of 1000000 ops over 10 runs: 458ms
[code]....
Comparatively, peenut's approach is almost 200ms faster when executed 1,000,000 times in a tight loop, so his approach wins out.
what's the main difference between a Class and a Type and a ValueType.and is a Delegate a Type? or an eventhandler/event (the actual event itself)is every object a type? or is it only true in VB
View 3 RepliesDoes anyone know of a fast way in VB to go from a string to a generic type T constrained to a valuetype (Of T as Structure), when I know that T will always be some number type?This is too slow for my taste:
Return DirectCast(Convert.ChangeType(myStr, GetType(T)), T)
But it seems to be the only sane method of getting from a String --> T. I've tried using Reflector to see how Convert.ChangeType works, and while I can convert from the String to a given number type via a hacked-up version of that code, I have no idea how to jam that type back into T so it can be returned.
I'll add that part of the speed penalty I'm seeing (in a timing loop) is because the return value is getting assigned to a Nullable(Of T) value. If I strongly-type my class for a specific number type (i.e., UInt16), then I can vastly increase the performance, but then the class would need to be duplicated for each numeric type that I use.
It'd almost be nice if there was converter to/from T while working on it in a generic method/class. Maybe there is and I'm oblivious to its existence?
Conclusion:Testing the three provided implementations below and my original DirectCast/ChangeType form, @peenut's approach of using a prepared delegate to fetch the Parse method from a basic type works. No error checking is done, however, so implementors need to remember to only use this with valuetypes that have a Parse method available. Or extend the below to do error checking.
All runs were done on a 32bit system running Windows Server 2003 R2 with 4GB of RAM. Each "run" is 1,000,000 executions (ops) of the method to be tested, timed with StopWatch and reported back in milliseconds.
Original DirectCast(Convert.ChangeType(myStr, GetType(T)), T):
1000000 ops: 597ms
Average of 1000000 ops over 10 runs: 472ms
Average of 1000000 ops over 10 runs: 458ms
[code]....
Using System.Reflection and calling InvokeMethod to get at the Parse method:
1000000 ops: 12213ms
Average of 1000000 ops over 10 runs: 11468ms
Average of 1000000 ops over 10 runs: 11509ms
Average of 1000000 ops over 10 runs: 11524ms
[code]....
Konrad's approach to generate IL code to access the Parse method and store the call into a delegate:
1000000 ops: 352ms
Average of 1000000 ops over 10 runs: 316ms
Average of 1000000 ops over 10 runs: 315ms
[code]....
peenut's approach of using a delegate to access the Parse method directly:
1000000 ops: 272ms
Average of 1000000 ops over 10 runs: 272ms
Average of 1000000 ops over 10 runs: 275ms
[code]....
Comparatively, peenut's approach is almost 200ms faster when executed 1,000,000 times in a tight loop, so his approach wins out. Although, Konrad's wasn't far behind and is itself a fascinating study of things like ILGenerator.
Write an overload for every numeric type or if possible constrain a generic extension method to just numeric types.
View 2 Replies