Xavier Peña Xavier Peña - 2 months ago 19
C# Question

How to get TypeCode of an Array of byte?

I need to tell the type of an unknown variable.

Type.GetTypeCode()
seems good enough for my purposes, but in the case of
byte[]
it does not provided the desired result.

Here is the simplified code for my problem:

var bytes = new byte[10];
var typeCode = Type.GetTypeCode(bytes.GetType());

// Actual result: typeCode equals Object
// Desired result (pseudocode): "array of TypeCode.Byte"

Answer

TypeCode is an enumeration, and given there is no enum member representing "array of Byte", you'll get TypeCode.Object, because:

Object
A general type representing any reference or value type not explicitly represented by another TypeCode.

You're probably looking for Type.GetElementType(), as that returns:

The Type of the object encompassed or referred to by the current array [...]

Using that returned Type you then in turn can call Type.GetTypeCode():

var byteArray = new byte[0];

Type arrayType = byteArray.GetType();
Type elementType =  arrayType.GetElementType();
TypeCode elementTypeCode = Type.GetTypeCode(elementType);

Here, elementTypeCode will be TypeCode.Byte.

Comments