PointersAndWorkaroundsVB 1.0.4
dotnet add package PointersAndWorkaroundsVB --version 1.0.4
NuGet\Install-Package PointersAndWorkaroundsVB -Version 1.0.4
<PackageReference Include="PointersAndWorkaroundsVB" Version="1.0.4" />
<PackageVersion Include="PointersAndWorkaroundsVB" Version="1.0.4" />
<PackageReference Include="PointersAndWorkaroundsVB" />
paket add PointersAndWorkaroundsVB --version 1.0.4
#r "nuget: PointersAndWorkaroundsVB, 1.0.4"
#:package PointersAndWorkaroundsVB@1.0.4
#addin nuget:?package=PointersAndWorkaroundsVB&version=1.0.4
#tool nuget:?package=PointersAndWorkaroundsVB&version=1.0.4
PointersAndWorkaroundsVB
Not just a pointer library, but a full comprehensive library tailored for VB.NET.
New in version 1.0.3: Added a static class named
SizeOfthat provides compile-time constants for common CLI types, allowing for cross-platform type size calculations, memory layout planning, and buffer calculations.
This NuGet package provides VB.NET developers with C#-like features including safe pointer operations, functional programming utilities, tuple deconstruction, workarounds for VB.NET limitations, and in version 1.0.4, parameter validation.
The library aims to bridge the gap between VB.NET and C# features, enabling VB.NET developers to make full use of modern programming features while maintaining the safety and simplicity of the VB.NET language.
Requirements
Features
🔧 Pointer Operations
- Safe pointer management for VB.NET developers
- Enhanced MemoryBlock class with zero-initialization, span support, and array copying
- Typed pointers with bounds checking
- Array pinning to prevent GC movement
- Memory block creation from existing pointers
🧮 Functional Programming
- Pattern matching expressions
- Function composition and method chaining
- Memoization for expensive computations
- Currying and partial function application
- Pipeline operators for fluent APIs
🔄 Workarounds
- Value swapping with reference parameters
- Assignments with return values
- Type matching utilities
- Async iteration with loop control
- MakeAsyncEnumerable for converting iterator functions to async enumerables
- Safe array slicing with bounds checking
- Loop signal control for fine-grained iteration control
DoWithextension method to perform actions with a value (see Quick Start → Workarounds; note that VB.NET Structure values must be updated manually in the callback)
✅ Parameter Validation
- Declarative validation using attributes
- Multiple validation rules including null, empty, numeric, string validation
- Custom constraints like length ranges, value ranges, regex patterns
- Built-in validators for email, URL, and common patterns
- Reflection-based validation for automatic parameter checking
📦 Tuple Deconstruction
- Value tuple extensions for VB.NET
- Deconstruction helpers for 2-5 element tuples
- Type-safe tuple operations
📐 Type Size Constants
SizeOfstatic class provides compile-time constants for common CLI types- Cross-platform type size calculations
- Memory layout planning and buffer calculations
Installation
# Package Manager
Install-Package PointersAndWorkaroundsVB
# .NET CLI
dotnet add package PointersAndWorkaroundsVB
# Package Reference
<PackageReference Include="PointersAndWorkaroundsVB" Version="1.0.0" />
Quick Start
Pointer Operations
Imports PointersAndWorkaroundsVB
' Create a pointer from an array
Dim numbers() As Integer = {1, 2, 3, 4, 5}
Dim ptr = Pointer.Create(numbers)
' Access elements safely
For i As Integer = 0 To Pointer.UBound(ptr)
Console.WriteLine(ptr(i))
Next
' Memory block allocation
Using memoryBlock As New MemoryBlock(1024)
' Use the memory block for unmanaged operations
Dim intPtr = memoryBlock.AsPointer(Of Integer)(256)
' ... work with the pointer
End Using
Functional Programming
Imports PointersAndWorkaroundsVB
' Pattern matching
Dim result = (3.5F).PatternMatch(
(Function(x) x < 0, "Negative"),
(Function(x) x = 0, "Zero"),
(Function(x) x > 0, "Positive")
)
' Function composition
Dim transform = (Function(x As Integer) x).Compose(
Function(n) n * 2,
Function(n) n + 1,
Function(n) n.ToString()
)
' Memoization
Dim expensiveFunction = Function(x As Integer)
' Expensive computation here
Return x * x
End Function
Dim memoized = expensiveFunction.Memoize()
Workarounds
Imports PointersAndWorkaroundsVB
' Value swapping
Dim a = 10, b = 20
Workarounds.Swap(a, b)
' Assignment with return value
Dim value = Workarounds.Assign(a, 42)
' Type matching
If Workarounds.TryMatchType(someObject, value) Then
' Use the typed value
End If
' Safe array slicing
Dim original As Integer() = {1, 2, 3, 4, 5}
Dim slice = Workarounds.Slice(original, 1, 3)
' Loop control with LoopSignal
Dim numbers() As Integer = {1, 2, 3, 4, 5}
Dim asyncNums = Await Workarounds.MakeAsyncEnumerable(
Iterator Function()
For Each n In numbers
Yield n
Next
End Function)
Await asyncNums.ForEachAsync(Function(num)
If num = 3 Then Return LoopSignal.Continue ' Skip 3
If num = 5 Then Return LoopSignal.Break ' Stop at 5
Console.WriteLine(num)
Return LoopSignal.Normal
End Function)
' New in 1.0.4: `DoWith` extension method to perform actions with a value.
' Important: VB.NET Structure values must be updated manually in the callback;
' Classes are not affected, however.
Dim myVector As New Vector2(3, 5) ' from `System.Numerics` namespace
myVector.DoWith(Sub(vec)
vec += New Vector2(1, 2)
Console.WriteLine($"Coordinate: {vec}")
myVector = vec ' Update the vector value
End Sub)
' Extra note: If you want to keep the original value, no need to update it.
Enhanced MemoryBlock Features
Imports PointersAndWorkaroundsVB
' Create memory block with zero initialization
Using memoryBlock As New MemoryBlock(1024, zeroMemory:=True)
' Copy data from managed array
Dim sourceData() As Integer = {1, 2, 3, 4, 5}
memoryBlock.CopyFrom(sourceData)
' Work with spans for safe access
Dim span = memoryBlock.AsSpan(Of Integer)(5)
For i As Integer = 0 To span.Length - 1
span(i) *= 2 ' Modify data through span
Next i
' Copy data back to managed array
Dim resultData(4) As Integer
memoryBlock.CopyTo(resultData)
End Using
' Create memory block from existing pointer (advanced usage)
Using existingPtr As Pointer(Of Integer) = GetSomePointer()
Dim referencedBlock = MemoryBlock.FromPointer(existingPtr, 256)
' ... then work with the referenced block
End Using
Async Enumerable Support
Imports PointersAndWorkaroundsVB
' Convert iterator function to async enumerable (for .NET 8.0 & .NET 9.0)
' NOTE: For .NET 10.0, DO NOT USE the `Await` keyword.
Dim asyncNumbers = Await Workarounds.MakeAsyncEnumerable(
Iterator Function()
For i = 1 To 10 : Yield i : Next i
End Function)
' Use with async iteration
Await asyncNumbers.ForEachAsync(Function(num)
Console.WriteLine($"Processing number: {num}")
Return LoopSignal.Normal
End Function)
Parameter Validation
Imports PointersAndWorkaroundsVB
' Simple parameter validation using attributes
Public Sub ProcessUser(
<ValidateParam(ValidationRule.NotNullOrEmpty)> username As String,
<ValidateParam(ValidationRule.Email)> email As String,
<ValidateParam(ValidationRule.AlwaysPositive)> age As Integer)
' Parameters are automatically validated before method execution
Console.WriteLine($"Processing user: {username}, {email}, {age}")
End Sub
' Advanced validation with custom constraints
Public Sub ProcessData(
<ValidateParam(ValidationRule.NotNullOrEmpty, MinLength:=3, MaxLength:=50)> name As String,
<ValidateParam(ValidationRule.AlwaysPositive, MinValue:=18, MaxValue:=120)> age As Integer,
<ValidateParam(ValidationRule.Url)> website As String)
' All validation rules are checked automatically
Console.WriteLine($"Processing: {name}, {age}, {website}")
End Sub
' Manual validation using ParameterValidator
Public Sub ValidateManually(value As String)
ParameterValidator.Validate(
value,
ValidationRule.NotNullOrWhitespace,
"value",
minLength:=5,
maxLength:=100
)
' Continue with validated value
End Sub
' Validate all parameters of a method using reflection
Public Sub ValidateMethodParameters()
Dim methodInfo = GetType(MyClass).GetMethod("ProcessUser")
Dim parameters = {"john_doe", "john@example.com", 25}
ParameterValidation.ValidateParameters(methodInfo, parameters)
' All parameters are validated automatically
End Sub
' Combined validation rules
Public Sub ProcessComplexData(
<ValidateParam(ValidationRule.NotNullOrEmpty Or ValidationRule.NotWhitespace,
MinLength:=5, MaxLength:=100)> description As String,
<ValidateParam(ValidationRule.AlwaysPositive,
MinValue:=0, MaxValue:=100)> percentage As Double,
<ValidateParam(ValidationRule.Finite)> measurement As Double)
' Multiple validation rules applied automatically
Console.WriteLine($"Processing: {description}, {percentage}%, {measurement}")
End Sub
Tuple Deconstruction
Option Strict On
Option Infer On
Imports PointersAndWorkaroundsVB
Dim person = ("John", "Doe", 30)
' Deconstruct the tuple (ideal syntax, currently not supported)
'Dim (firstName, lastName, age) = person
' It is REALISTIC to write:
Dim firstName As String, lastName As String, age As Integer
person.Deconstruct(firstName, lastName, age)
Type Size Constants
Imports PointersAndWorkaroundsVB
' Calculate buffer sizes for data structures
Dim bufferSize As Integer = SizeOf.Integer + (SizeOf.Double * 10) + SizeOf.Boolean
' Calculate memory layout
Dim structSize As Integer = SizeOf.Integer + SizeOf.Long + SizeOf.Char
' Use in unsafe code scenarios
Using memory As New MemoryBlock(SizeOf.Integer * 100)
' Allocate space for 100 integers
End Using
' Binary serialization helpers
Dim floatCount As Integer = totalBytes \ SizeOf.Single
Dim doubleCount As Integer = totalBytes \ SizeOf.Double
Loop Signal Control
Imports PointersAndWorkaroundsVB
' LoopSignal provides fine-grained control over async iterations:
' - Normal: Continue with normal iteration
' - Continue: Skip to next iteration
' - Break: Exit the loop immediately
Await someAsyncEnumerable.ForEachAsync(Function(item)
If ShouldSkip(item) Then Return LoopSignal.Continue
If ShouldStop(item) Then Return LoopSignal.Break
Process(item)
Return LoopSignal.Normal
End Function)
API Reference
LoopSignal Enum
LoopSignal.Normal- Continue with normal iteration behaviorLoopSignal.Continue- Skip to next iteration immediatelyLoopSignal.Break- Exit the loop immediately
SizeOf Class
Static class providing compile-time constants for CLI type sizes (in bytes):
| Constant | Type | Size (bytes) |
|---|---|---|
SizeOf.Integer |
Int32 | 4 |
SizeOf.UInteger |
UInt32 | 4 |
SizeOf.Long |
Int64 | 8 |
SizeOf.ULong |
UInt64 | 8 |
SizeOf.Short |
Int16 | 2 |
SizeOf.UShort |
UInt16 | 2 |
SizeOf.Byte |
Byte | 1 |
SizeOf.SByte |
SByte | 1 |
SizeOf.Single |
Single (float) | 4 |
SizeOf.Double |
Double | 8 |
SizeOf.Decimal |
Decimal | 16 |
SizeOf.Char |
Char | 2 |
SizeOf.Boolean |
Boolean | 1 |
Pointer Class
Pointer.Create(array)- Create a typed pointer from an arrayPointer.UBound(ptr)- Get the upper bound of a pointerPointer<T>- Generic pointer class with indexer access
MemoryBlock Class
MemoryBlock(sizeInBytes, zeroMemory)- Allocate unmanaged memory with optional zero initializationMemoryBlock.Allocate<T>(elementCount)- Type-safe allocationMemoryBlock.FromPointer<T>(pointer, sizeInBytes)- Create memory block from existing Pointer(Of T)AsPointer<T>(elementCount)- Create typed pointer from memory blockFill(byte)/Fill<T>(T)- Fill memory with byte or typed valueCopyFrom<T>(array)- Copy data from managed array to memory blockCopyTo<T>(array)- Copy data from memory block to managed arrayAsSpan<T>(elementCount)- Create span for safe memory accessAsReadOnlySpan<T>(elementCount)- Create read-only span for safe memory access
Workarounds Module
Swap(ref T, ref T)- Swap two values of any typeAssign(ref T, T)- Assign with return value (enables chained assignments)TryMatchType(object, out T)- Type-safe pattern matchingMakeAsyncEnumerable(enumerableFunc)- Convert iterator function to async enumerableForEachAsync- Async iteration with loop control signalsSlice(array, start, end)- Safe array slicing with bounds checkingSlice(list, start, end)- Safe list slicing with bounds checking
Parameter Validation APIs
ValidateParamAttribute- Declarative parameter validation using attributesValidationRule- Enum with validation rules (NotNull, NotEmpty, AlwaysPositive, Email, Url, etc.)ParameterValidation.ValidateParameters(method, values)- Validate all method parameters using reflectionParameterValidation.Validate(value, rules, ...)- Manual parameter validation- Custom constraints:
MinLength,MaxLength,MinValue,MaxValue,RegexPattern
Parameter Validation Rules (as in ValidationRule enum):
NotNull- Parameter must not be nullNotEqualToZero- Parameter must not be zeroNonNegative- Parameter must be >= 0NonPositive- Parameter must be ⇐ 0AlwaysPositive- Parameter must be > 0AlwaysNegative- Parameter must be < 0NotEmpty- Parameter must not be empty (strings/collections)NotNullOrEmpty- Not null and not emptyNotWhitespace- Parameter must not be whitespace (strings)NotNullOrWhitespace- Not null, not empty, not whitespaceNotDefault- Parameter must not be default value for its typeNotNaN- Parameter must not be NaN (floating-point)Finite- Parameter must be finite (not NaN or infinity)Email- Parameter must be valid email addressUrl- Parameter must be valid URL
FunctionalExtensions Module
PatternMatch- Pattern matching expressions with predicate-result pairsCompose- Function composition for chaining transformationsMemoize- Function memoization for caching expensive computationsCurry- Partial function application (currying)Pipe- Pipeline operator simulation for fluent method chaining
ValueTupleExtensions Module
Deconstruct- Deconstruction methods for 2-5 element tuples
Advanced Usage
Combining Functional Extensions with Workarounds
Imports PointersAndWorkaroundsVB
' Compose multiple operations with pattern matching
Dim result = 42.5F _
.Pipe(Function(x) x * 2) _
.PatternMatch(
(Function(x) x < 0, "Negative"),
(Function(x) x >= 0 AndAlso x < 100, "Small"),
(Function(x) x >= 100, "Large")
)
Using SizeOf for Binary Protocol Implementation
Imports PointersAndWorkaroundsVB
' Calculate exact message size for a protocol
Dim messageSize As Integer =
SizeOf.Integer + ' Message ID
SizeOf.Integer + ' Timestamp
SizeOf.Integer + ' Payload length
payload.Length * SizeOf.Byte ' Actual payload
' Allocate appropriate buffer
Using buffer As New MemoryBlock(messageSize, zeroMemory:=True)
' ... write message fields
End Using
Advanced Async Iteration Patterns
Imports PointersAndWorkaroundsVB
' Batch processing with early termination
Await largeDataset.ToAsyncEnumerable().ForEachAsync(Function(item)
If Not IsValid(item) Then Return LoopSignal.Continue
ProcessBatch(item)
batchCount += 1
If batchCount >= maxBatchSize Then Return LoopSignal.Break
Return LoopSignal.Normal
End Function)
Tuple Deconstruction in Complex Scenarios
Option Strict On
Option Infer On
Imports PointersAndWorkaroundsVB
' Multiple tuple deconstruction
Dim record = ("Alice", "Johnson", 28, "NYC", 50000D)
Dim firstName, lastName, city As String
Dim age As Integer
Dim salary As Double
record.Deconstruct(firstName, lastName, age, city, salary)
' Useful for swapping tuple values
Dim pair = (100, 200)
Dim a, b As Integer
pair.Deconstruct(a, b)
Workarounds.Swap(a, b) ' Now a=200, b=100
Contributing
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
Support
If you encounter any issues or have questions, please open an issue on the GitHub repository.
License
This project is licensed under the MIT License. See the LICENSE file for details.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.