Generic BitConverter.GetBytes For Primitive Data Types?

Jan 19, 2012

addressing the need for getting the bytes of an object. But I am wondering if there is an approach to calling BitConverter.GetBytes on a generic type where I know the type is a primitive (Int32, UInt16, etc).

Public Sub Foobar(Of T as Structure)()
Dim x as T 'Assume T is declared as Int32
Dim y() as Byte
y = System.BitConverter.GetBytes(x)
End Sub

The above will throw your usual error:

Overload resolution failed because no accessible 'GetBytes' can be called with these arguments:
'Public Shared Function GetBytes(value As Double) As Byte()': Value of type 'T' cannot be converted to 'Double'.
'Public Shared Function GetBytes(value As Single) As Byte()': Value of type 'T' cannot be converted to 'Single'.

[code]....

One solution I think would work is a large Select Case calling GetType(), but that is horrendously slow (because of boxing) and looks ugly. I would think that since I call my higher level class with a primitive data type for T, that the compiler would be smart enough to figure it out, but I assume I am not providing enough information for it to derive what T's underlying value is at compile time for the invoked instances.

View 6 Replies


ADVERTISEMENT

Primitive Types - .Net Anding A Byte And A Double?

Aug 1, 2011

during some code conversion from another persons VB.net project to C#, i have come across the following code:

[Code]...

Now m trying to convert this to C#, but im a little confused as to exactly the meaning of this line:

If lbytRelayStateMask And (2 ^ lintCounter) Then It appears there something going on behind the scenes (that ill have to examine further) however before i do i would just like to clarify the result of this if statement. Am i correct in saying if either one of the sub-expressions equals zero then its false, otherwise its true? Sorry, im not too up to speed on VB.net.

View 2 Replies

Specific Method For Getting Non-primitive Types In An Assembly?

Mar 11, 2011

Is there any class or specific method for getting non-primitive types in an assembly? FieldInfo.Gettype() will do for primtive types but what about non-primitive types?

View 3 Replies

C# - From A List<object> , ToString() Them Just When They Are Primitive Types Or Have This Method Overridden??

Feb 15, 2011

Given a list of objects, I'd like to print a string version of them just in case the object.ToString() result is a relevant string.By that I mean I don't want to get things like:

obj.ToString() -> System.Collections.Generic.List`1[MyLib.Dude]
obj.ToString() -> System.Collections.Generic.Dictionary`2[System.Int32,System.DateTime]
obj.ToString() -> System.Byte[]

But I want to get things like:

obj.ToString() -> Hi
obj.ToString() -> 129847.123
obj.ToString() -> Id = 123

What should be the best way to implement this in a method:

Public Sub PrintInterestingStuffOnly(ByVal coolList as Ilist(Of Object))
For Each obj in coolList
'insert solution here

[code].....

View 3 Replies

Extend Primitive Types Such As System.String And System.Int32?

Jul 25, 2010

Is it possible to extend primitive types such as System.String and System.Int32 (IE: integer) in .Net 4 and if so how?

To be more specific, I am aware of the concept of partial classes but this doesnt seem to be the answer. Also I find that System.String is not inheritable and Int32 is a structure.

Lastly I am interested in knowing both a VB.Net and C# answer to the above question.

View 2 Replies

BitConverter - Sending Data Across TCP Socket

Apr 9, 2010

Given the following information
Public Enum Request As Byte
None = 0
Identity = 1
License = 2
End Enum
Protected mType As Communication.Request
mType = Communication.Request.Identity
Debug.Print (BitConverter.GetBytes(mType).Length.tostring)
2

Why does bitconverter report that mType is a length of 2. I would have thought that passing a Byte into BitConverter.GetBytes would just return the Byte. I mean it's no big deal because it's only sending a very small block of data across a TCP Socket, but I'm just intrigued why it thinks it's 2 bytes.

View 1 Replies

C# - Default Value Of "value" In Primitive Types

Jun 23, 2009

primitive types (integer, string, etc) are now classes. However to access the value of the class you just use the object name (ex, x=y). It isn't necessary to refer to a property of the class (x.value = y.value).

[Code]...

View 3 Replies

.net - Casting Generic Types?

Apr 20, 2010

Public Function CastToT(Of T)(ByVal GenericType(Of Object) data) As GenericType(Of T)Return DirectCast(data, GenericType(Of T))End Function

The above clearly does not work. Is there any way to perform this cast if I know that all objects inside data are in fact of Type T?

View 2 Replies

Define A Generic That Can Take Several Possible Value Types?

May 4, 2011

Is there any way to define a Generic in VB.NET which will accept only Singles or Doubles? I tried the following things, based on what I've found online, but none compile:

Dim target As Nullable(Of {Single, Double})
Dim target As Nullable(Of T As {Single, Double})
Dim target As Nullable(Of T {Single, Double})
Dim target As Nullable(Of Single, Double)
Dim target As Nullable(Of T As Single, Double)

I want to specify that target can either be a Single? or a Double? only.

View 1 Replies

GetType On Generic Types

Dec 2, 2010

I'm trying register presenters with Windsor using the convention based method but trying to do this in VB.NET, but the problem is it does not want to compile this statement:

Dim type = GetType(AbstractPresenter(Of))

I am getting : Too few type arguments to AbstractPresenter(Of TView, TPresenter)

Which I don't understand because this is a valid statement according to question. Also showing valid in other C# to VB.NET converters when converting typeof(AbstractPresenter<>).

View 1 Replies

Specify Generic Types On Delegates?

Nov 15, 2010

Maybe I am just not reading the MSDN documentation correctly, but given a function that takes in one string parameter and returns type T, how can this be specifed as a shared function using Func()?

MSDN says Func(Of In T1, Out TResult), but all of their examples use the same data type, i.e., Func(Of String, String). I want to do Func(Of In String, Out T), where T is arbitrary (but I can constrain it if necessary by a base class). I want it shared/static at the class level, yet the encapsulating class will itself not be a generic class. It seems in this specific scenario, it's impossible to do what I want because the compiler would have no way of knowing what Type T is at runtime.

So is it possible to do generics on delegates or anonymous lambda expressions in VB.net (not C#)?

View 1 Replies

.net - Retrieving Generic Argument Types

Oct 23, 2009

I am using VB.Net. I have an object class called clsA(of T as clsB). Depending on what T is, I want to do different things. Let's say that clsC and clsD both inherit clsB and therefore can be used for T.

If I have an instance of clsA(of clsC), how can I get the inside type (i.e. clsC) using reflection?

View 4 Replies

Arrays And Generic Types - Conversion

May 10, 2011

Well this is maybe a little different than other array based conversion questions, but I'm dealing with forced typing concerns due to interface implementation and thus would like a few opinions on the process. I've basically redesigned the Collection suite for .Net because I don't like the extreme simplicity of the default Collections and dictionaries, as well, when I want the more complex concepts I don't want to have rewrite the same collection over an over again.

[Code]...

View 2 Replies

C# - What Are All Of The Generic Collections/types In The 4.0 .NET Framework

Nov 29, 2010

Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

View 6 Replies

Use A Generic That Only Accepts Integer Types?

Mar 5, 2010

Is there a way to use a generic that only accepts integer types?

I have a Clamp(value, min, max) function, and it would be nice if it could accept ints, uints, floats, shorts, ect without having to write an individual function for each type.

View 1 Replies

C# ::Generic Overkill To Define Multiple T Types?

May 25, 2011

NOTE: I am mixing VB and C# - snippets come from different librariesI have a VB class definition as follows:

Public Class Session(Of TConnectionBuilder As {DbConnectionStringBuilder, New}, _
TConnection As {DbConnection, New}, _
TDataReader As {DbDataReader})

[code].....

View 3 Replies

Use Generic Constraints Based On Attributes Rather Than Types?

Aug 28, 2009

I'm trying to write a class that will be in charge of persisting application options. Since the options need to be persisted the values that I'm sent must be serialisable.

Initially I thought I've be able to write a method with a signature like this[code]...

View 4 Replies

How To Match Generic Types, Without The Type Parameter In A IF-ELSE Statement

Jan 23, 2009

I have bee trying to figure out, how to match generic types, without the type parameter in a IF-ELSE statement - heres what i mean:

<P>IF TypeOf(Obj) Is GenericTypeExample(Of ???Any???) Then</P>
<P>End if</P>

View 7 Replies

Write A Generic Function In .NET That Only Accepts Numerical Types?

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

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

Error - Soap Serializer Does Not Support Serializing Generic Types : System.Nullable`1[System.DateTime]

Oct 2, 2009

Im working on my first n-tier application. I am trying to serialize a structure and Im getting an error"Soap Serializer does not support serializing Generic Types : System.Nullable`1[System.DateTime]."Here is the structure that is being serialized
Namespace Structures

<Serializable()> _
Public Structure structAllergy
Public AllergyID As String
Public ProfileID As String

[code]....

The bold line is the line that is throwing the error.

View 1 Replies

Constrain A Generic Method / Extension Method To Numeric TYPEs Only?

Sep 16, 2010

Write an overload for every numeric type or if possible constrain a generic extension method to just numeric types.

View 2 Replies

Byte Array To Integer With Bitconverter?

Dec 27, 2011

I am new to vb net so please cut me some slack if this is a stupid question, I have always used vb6 before, but finding that its less and less supported so trying to learn vb.net by myself. Also I am doing this for a hobby not a profession.I am writing an Console application to read a file sequentially 1 byte at a time into a 1 byte buffer. It then copies that byte into a 4 byte lookup buffer, that moves, ie as the file pointer moves forward by one byte the 4 byte lookup buffer copies the last 3 bytes into the first 3 bytes to accept the byte at the file pointer into the 4th byte of the lookup buffer. I am doing 1 byte at a time because the data I am looking for is not at pre-determind offsets and filesizes may not be a multiple of 4.

[Code]...

Help please its driving me mad It appears as if the byte is not being transferred to the lookup buffer so that it would always be 0, either that or I am not converting it to an integer properly

View 5 Replies

C# - Use-cases For IsLittleEndian In BitConverter Class?

Jun 20, 2011

I was so happy when I discovered IsLittleEndian field in BitConverter. I thought of course it should be there and I should be able to specify whatever endian I like. Well, my happiness didn't last long. Spent some time till found out that there is no way to set the field.The field is readonly, and it is only set to true in static constructor:

[Code]...

My question is: how come there is very useful piece of code that is already implemented and sitting there in the FCL, but there is no way to use it (unless you start messing with reflection of course)? Is it just because some developers didn't meet the deadline and left the job half-done? Even if so, why the code is not available, but the field is?I hope there is a good reason for this.

I want to make myself clear. I don't need a solution on how to handle big-endian values. I do have a solution. The solution is actually shown in my question.

View 6 Replies

"Nominal Storage Allocation" In The Context Of Primitive Data Type Allocation Size?

Jul 30, 2011

Looking at this table describing the data types in VB.One of the columns is labeled "Nominal storage allocation". What does this mean? Why is the word "nominal" here?

View 2 Replies

Is There A Concept Of "Generic Structure" Similar To Generic Collections, Generic Classes

Dec 16, 2009

We have migrated our Vb6 application to VB.NET using a third party tool. Now we are in a process of Refactoring and introducing object oriented concepts in the application.

In VB6, we were using structures in many places. As a part of introducing object oriented programming,

1. is it a good idea of changing all Structures to Classes? or Is there a concept of "Generic Structure" similar to Generic collections, Generic classes?

2. Can some one guide me any source containing guide lines or best practices for applications that are migrated to VB.NET from VB6 and implementing object oriented programmaing.

View 3 Replies

C# - Use Flush Parameter With Encoder.GetBytes Method?

Oct 4, 2010

This link explains the Encoder.GetBytes Method and there is a bool parameter called flush explained too . The explanation of flush is : true if this encoder can flush its state at the end of the conversion; otherwise, false. To ensure correct termination of a sequence of blocks of encoded bytes, the last call to GetBytes can specify a value of true for flush.but I didn't understand what flush does?

View 3 Replies

C# - What 'length' Parameter Should I Pass To SqlDataReader.GetBytes()?

Feb 7, 2011

I have a SqlDataReader and need to read a varbinary(max) column from it using the SqlDataReader.GetBytes() method. This method populates a byte array and therefore needs to know what length of data to read.This is where I get confused.. Clearly I want to read all the data that has been returned from the database in this row/column so what 'length' parameter should I pass?As far as I can see, the SqlDataReader doesn't provide any methods to discover what length of data is available, therefore this method seems fairly awkward to me.I'm tempted to just pass int.MaxValue here and forget about the issue but something about this doesn't sit right with me.

I am aware that I can instead call

byte[] value = (byte[])dataReader["columnName"];

.. and this seems to completely take care of the length issue internally. However I am working with a set of complicated code generation templates that have been built around the SqlDataReader.GetXXXX() methods. So I am tied into using GetBytes and need to understand its proper usage.

View 7 Replies

C# - What 'length' Parameter Should Pass To SqlDataReader.GetBytes()

Jun 21, 2012

I have a SqlDataReader and need to read a varbinary(max) column from it using the SqlDataReader.GetBytes() method. This method populates a byte array and therefore needs to know what length of data to read.This is where I get confused.. Clearly I want to read all the data that has been returned from the database in this row/column so what 'length' parameter should I pass?As far as I can see, the SqlDataReader doesn't provide any methods to discover what length of data is available, therefore this method seems fairly awkward to me.I'm tempted to just pass int.MaxValue here and forget about the issue but something about this doesn't sit right with me.

View 2 Replies

Why Encoding.Default.GetBytes() Returns Different Results In C#

May 29, 2009

We recently came across some sample code from a vendor for hashing a secret key for a web service call, their sample was in VB.NET which we converted to C#. This caused the hashing to produce different input. It turns out the way they were generating the key for the encryption was by converting a char array to a string and back to a byte array. This led me to the discovery that VB.NET and C#'s default encoder work differently with some characters.

C#:
Console.Write(Encoding.Default.GetBytes(new char[] { (char)149 })[0]);

VB:
Dim b As Char() = {Chr(149)}
Console.WriteLine(Encoding.Default.GetBytes(b)(0))

The C# output is 63, while VB is the correct byte value of 149.if you use any other value, like 145, etc, the output matches.Walking through the debugging, both VB and C# default encoder is SBCSCodePageEncoding.I have corrected the sample code by directly initializing a byte array, which it should have been in the first place, but I still want to know why the encoder, which should not be language specific, appears to be just that.

View 5 Replies







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