Xavier Peña Xavier Peña - 10 months ago 85
C# Question

How to get TypeCode of an Array of byte?

I need to tell the type of an unknown variable.

seems good enough for my purposes, but in the case of
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 Source

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

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.