Class DType
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
NumSharp's data-type descriptor — the INSTANCE of a DTypeMeta class, standing in for NumPy's
numpy.dtype object (np.dtype('f8'), np.dtype('M8[ns]')), and the single dtype
spelling every dtype-taking API in NumSharp accepts.
public sealed class DType : IEquatable<DType>
- Inheritance
-
DType
- Implements
- Inherited Members
Remarks
Two levels (NEP 41/42). The CLASS (Meta — np.dtypes.Float64DType) owns the
behaviour: promotion, casting, the default instance; the INSTANCE owns the parameters: byteorder
and, for the parametric datetime pair, the unit (DatetimeMetadata). The 15 storage-backed
builtins have one canonical instance each (np.dtype("i8") is the same object every time —
isbuiltin == 1); a datetime descriptor or a non-native-byte-order one is a fresh object
(isbuiltin == 0), exactly as in NumPy.
Why it exists. NumPy funnels every dtype= argument through one coercion point,
numpy.dtype(...), so a Python type (float), a NumPy scalar type (np.float32),
a np.dtype instance and a dtype string ('float32', 'f4', '<f8')
are ALL valid there. NumSharp historically had three separate spellings — a C# Type,
an NPTypeCode enum, and this descriptor from dtype(string, bool, bool, IReadOnlyDictionary<string, object>) — which forced
two-or-three overloads per function. DType collapses them: it is the one type every
dtype-taking overload accepts, and each of the other spellings converts to it IMPLICITLY, so a caller
writes whichever is convenient and it binds the single overload — mirroring NumPy's one dtype=.
The four spellings, all implicit. The following are equivalent and all bind the one
DType overload (e.g. np.sqrt(x, dtype: …)):
- Type —
typeof(float)(NumPy's Python/NumPy scalar type). - NPTypeCode —
NPTypeCode.Single(NumSharp's compact storage enum; no NumPy counterpart). - NumPy dtype string —
"float32"/"f4"/"<f8"/"M8[ns]"(NumPy'sdtype='float32'— see the casing rules below). - DType itself —
DType.Single,np.dtype("f4"),DType.From(...).
A <xref href="NumSharp.DType" data-throw-if-not-resolved="false"></xref> also converts back to <xref href="System.Type" data-throw-if-not-resolved="false"></xref> and <xref href="NumSharp.NPTypeCode" data-throw-if-not-resolved="false"></xref>
implicitly, so it drops straight into code expecting either — as long as its class has storage: a
datetime descriptor has none yet (Stage A), and converting one raises <xref href="System.NotSupportedException" data-throw-if-not-resolved="false"></xref>
rather than silently degrading to the "infer" state.
None / infer is null. A null DType is the
"none/infer" state — the analog of NumPy's dtype=None. This is precisely why DType
is a class, not a struct: a nullable DType dtype = null parameter is a drop-in replacement
for the old Type dtype = null parameter, so the engine's existing null idioms keep working
verbatim — dtype?.GetTypeCode() yields NPTypeCode? (null when none) and dtype == null
tests the none state. Converting a null/Empty spelling yields
a null DType (never a throwing conversion); the explicit
DType(Type) / DType(NPTypeCode) constructors, by contrast, reject
null/Empty (use a null DType for none).
NumPy string casing (source of truth: NumPy 2.5.4). Strings are parsed by dtype(string, bool, bool, IReadOnlyDictionary<string, object>) with NumPy's exact, case-sensitive grammar — the single-character codes differ by case:
| code | type |
|---|---|
| ? | bool |
| b / B | int8 / uint8 |
| h / H | int16 / uint16 |
| i / I | int32 / uint32 |
| q / Q | int64 / uint64 |
| e / f / d | float16 / float32 / float64 |
| D | complex128 |
| M8[unit] / m8[unit] | datetime64 / timedelta64 (descriptor-level in Stage A) |
Sized forms (<code>"i4"</code>, <code>"f8"</code>, <code>"c16"</code>), lowercase names (<code>"float64"</code>, <code>"int32"</code>,
<code>"complex128"</code>, <code>"datetime64[ns]"</code>) and byte-order prefixes (<code>"<f8"</code>, <code>">i4"</code>,
<code>"=u2"</code>, <code>"|b1"</code>) are all accepted; a non-native prefix (<code>">i4"</code> on this little-endian host) is
KEPT on the descriptor (<xref href="NumSharp.DType.byteorder" data-throw-if-not-resolved="false"></xref> <code>'>'</code>, <xref href="NumSharp.DType.isnative" data-throw-if-not-resolved="false"></xref> false) as NumPy does.
Deliberately narrowed to NumSharp's capability (the same narrowing as dtype(string, bool, bool, IReadOnlyDictionary<string, object>)):
only NumSharp's 15 element types and the two fixed-width string classes (S bytes, U
Unicode — one String storage lane, see StringDTypeMeta) can back an array.
Three consequences differ from NumPy and are intentional — (1) complex64 ('F', "c8",
"complex64") is rejected with NotSupportedException (NumSharp has only complex128), as are
structured / void / object dtypes; (2) NumSharp additionally accepts a superset of NumPy's
casing — the C# / NPTypeCode PascalCase names ("Int32", "Single",
"Boolean", "SByte", "Decimal", "Char") that NumPy 2.4.2 rejects — as a
convenience for C# callers; (3) datetime64/timedelta64 descriptors exist (parse, format,
promote, cast-check) but cannot allocate storage yet.
Descriptor surface (mirrors numpy.dtype): type (the C# Type),
typecode (NPTypeCode), Meta, num, name,
kind ('b'/'i'/'u'/'f'/'c'/'M'/'m'), char, itemsize,
alignment, byteorder, str, descr, isbuiltin,
isnative, hasobject, flags, metadata,
newbyteorder(string). Equality is structural (class + byte order + parameters) and null-safe;
Equals(object) additionally coerces a Type, an NPTypeCode or a
dtype string the way np.dtype('i4') == 'i4' does. ToString() is NumPy's str(dtype)
(int32, >i4, datetime64[ns]); ToString(bool) with repr: true is
repr(dtype) (dtype('int32'), dtype('<M8[ns]')).
np.sqrt(x, dtype: typeof(float)); // Type
np.sqrt(x, dtype: NPTypeCode.Single); // NPTypeCode enum
np.sqrt(x, dtype: "float32"); // NumPy string (== NumPy's dtype='float32')
np.sqrt(x, dtype: DType.Single); // DType spelling
np.sqrt(x); // dtype omitted == None / infer
DType d = np.dtype("<f8"); // full descriptor: d.type==typeof(double), d.kind=='f', d.itemsize==8
Type t = DType.Double; // implicit DType -> Type
NPTypeCode c = (DType)"int32"; // implicit string -> DType -> NPTypeCode
bool same = DType.Single == (DType)"f4"; // true — structural equality
DType m = np.dtype("M8[10ns]"); // datetime64[10ns]: m.kind=='M', np.datetime_data(m) == ("ns", 10)
Constructors
DType(NPTypeCode)
Builds a fresh descriptor for an NPTypeCode — a COPY of the class's canonical instance
(prefer From(NPTypeCode) / the implicit conversion, which return the singleton itself).
For the "none/infer" state use a null DType (this ctor throws on
Empty; the implicit NPTypeCode→DType conversion yields null).
public DType(NPTypeCode typecode)
Parameters
typecodeNPTypeCode
DType(Type)
Builds a fresh descriptor for a C# Type — a COPY of the class's canonical instance
(prefer From(Type) / the implicit conversion, which return the singleton itself).
For the "none/infer" state use a null DType (this ctor throws on a
null type; the implicit Type→DType conversion yields null).
public DType(Type type)
Parameters
typeType
Fields
NPY_BIG
NumPy's NPY_BIG ('>'): big-endian.
public const char NPY_BIG = '>'
Field Value
NPY_IGNORE
NumPy's NPY_IGNORE ('|'): byte order is not applicable — what every single-byte descriptor stores.
public const char NPY_IGNORE = '|'
Field Value
NPY_LITTLE
NumPy's NPY_LITTLE ('<'): little-endian.
public const char NPY_LITTLE = '<'
Field Value
NPY_NATBYTE
NumPy's NPY_NATBYTE: the explicit character of this host's byte order ('<' on little-endian
machines) — what str renders for a native descriptor and what swapping a non-native descriptor
produces. A static readonly field rather than a const: C fixes it at compile time, .NET at type
initialisation, which the JIT then treats as a constant.
public static readonly char NPY_NATBYTE
Field Value
NPY_NATIVE
NumPy's NPY_NATIVE ('='): "the byte order of this host", the form every parsed native descriptor
stores. A descriptor can also carry the host order EXPLICITLY (NPY_NATBYTE, what
newbyteorder('<') leaves on a little-endian host); both are native and compare equal, but the
explicit form shows in repr (dtype('<f8') instead of dtype('float64')).
public const char NPY_NATIVE = '='
Field Value
NPY_OPPBYTE
NumPy's NPY_OPPBYTE: the character of the OTHER byte order ('>' on little-endian machines) —
the only byte order that makes a descriptor non-native (PyArray_ISNBO(c) is c != NPY_OPPBYTE).
public static readonly char NPY_OPPBYTE
Field Value
NPY_SWAP
NumPy's NPY_SWAP ('s'): the newbyteorder request "swap the current order".
public const char NPY_SWAP = 's'
Field Value
byteorder
A character indicating the byte-order of this data-type object:
'=' native, '<' little-endian, '>' big-endian, '|' not applicable (single-byte types).
Only the NON-native order is ever stored explicitly (NumPy normalises the host's own order to '=').
public readonly char byteorder
Field Value
itemsize
The size of the dtype in bytes (itemsize). Per instance for the string classes (S5 → 5,
U5 → 20, the unsized S0/U0 → 0); the class's fixed size for every other class.
public readonly int itemsize
Field Value
kind
A character code (one of ‘biufcmMOSUV’) identifying the general kind of data:
b boolean, i signed integer, u unsigned integer, f floating-point,
c complex floating-point, m timedelta, M datetime, O object,
S (byte-)string, U Unicode, V void.
public readonly char kind
Field Value
name
NumPy's dtype.name spelling ("float32", "int64", "bool", "complex128",
"datetime64[ns]") — the CLR Type.Name ("Single") is not a NumPy name and does not
round-trip through dtype(string, bool, bool, IReadOnlyDictionary<string, object>). The NumSharp-only dtypes have no NumPy analog and get
lowercase names of their own ("decimal", "char") rather than the nearest NumPy stand-in.
public readonly string name
Field Value
type
The C# scalar type of one element (NumPy's dtype.type): string for U (NumPy's
np.str_), byte[] for S (NumPy's np.bytes_); null for a class with no C# scalar yet
(datetime64 in Stage A).
public readonly Type type
Field Value
typecode
The NumSharp storage discriminator; Empty for a class without storage (datetime64 in Stage A).
public readonly NPTypeCode typecode
Field Value
Properties
Boolean
The bool descriptor.
public static DType Boolean { get; }
Property Value
Byte
The byte (uint8) descriptor.
public static DType Byte { get; }
Property Value
Char
The char descriptor.
public static DType Char { get; }
Property Value
Complex
The Complex (complex128) descriptor.
public static DType Complex { get; }
Property Value
DatetimeMetadata
The instance parameters of a datetime64/timedelta64 descriptor (NumPy's c_metadata); null for every other class.
public DatetimeMetaData? DatetimeMetadata { get; }
Property Value
Decimal
The decimal descriptor.
public static DType Decimal { get; }
Property Value
Double
The double (float64) descriptor.
public static DType Double { get; }
Property Value
Half
The Half (float16) descriptor.
public static DType Half { get; }
Property Value
HasNAObject
True when this is a StringDType descriptor that has a missing-data object — the C# stand-in for
hasattr(dtype, 'na_object'), which tells "no sentinel" apart from a None sentinel (both make
na_object look like null, but only one of them exists).
public bool HasNAObject { get; }
Property Value
Int16
The short descriptor.
public static DType Int16 { get; }
Property Value
Int32
The int descriptor.
public static DType Int32 { get; }
Property Value
Int64
The long descriptor.
public static DType Int64 { get; }
Property Value
Meta
The DType CLASS this descriptor instantiates (type(np.dtype('f8'))): np.dtypes.Float64DType.
public DTypeMeta Meta { get; }
Property Value
SByte
The sbyte (int8) descriptor.
public static DType SByte { get; }
Property Value
Single
The float (float32) descriptor.
public static DType Single { get; }
Property Value
UInt16
The ushort descriptor.
public static DType UInt16 { get; }
Property Value
UInt32
The uint descriptor.
public static DType UInt32 { get; }
Property Value
UInt64
The ulong descriptor.
public static DType UInt64 { get; }
Property Value
alignment
The required alignment (bytes) of this data-type (dtype.alignment).
public int alignment { get; }
Property Value
base
dtype.base: the base of a sub-array dtype — this descriptor itself.
public DType @base { get; }
Property Value
char
A unique character code for each of the built-in types ('?' 'b' 'B' 'h' 'H' 'i' 'I' 'l' 'L' 'e' 'f' 'd' 'D'
'M' 'm' 'S' 'U'). Stored per descriptor, as in NumPy: the legacy spelling np.dtype('c') is an
S1 whose char is 'c' while np.dtype('S1').char is 'S' (the two still compare equal).
public char @char { get; }
Property Value
coerce
dtype.coerce of a StringDType descriptor: whether a stored value that is not a str is
converted to its str() (true, the default) or refused with NumPy's ValueError (false).
public bool coerce { get; }
Property Value
Exceptions
- AttributeError
The descriptor is not a
StringDType: NumPy's'numpy.dtypes.Float64DType' object has no attribute 'coerce'.
descr
The array-interface description (dtype.descr): one unnamed field carrying str — [('', '<i4')].
public IReadOnlyList<(string name, string typestr)> descr { get; }
Property Value
fields
dtype.fields: always null (no structured dtypes).
public IReadOnlyDictionary<string, (DType, int)> fields { get; }
Property Value
flags
dtype.flags: the item flags (NumPy's NPY_ITEM_REFCOUNT | NPY_NEEDS_INIT | …) — 107 for
StringDType, 8 (NPY_NEEDS_INIT) for U, 0 otherwise (ItemFlags).
public int flags { get; }
Property Value
hasobject
dtype.hasobject: whether items hold references that need clearing — true for StringDType (a cell
can own heap memory its array must free), false for every other class.
public bool hasobject { get; }
Property Value
isalignedstruct
dtype.isalignedstruct: whether a STRUCTURED dtype was built with align=True (C-struct
padding). False for every NumSharp descriptor, since none is structured — NumPy answers False for every
non-structured dtype too.
public bool isalignedstruct { get; }
Property Value
isbuiltin
dtype.isbuiltin: 1 for the canonical instance of a builtin class, 2 for a user-defined class (the
NumSharp-only Decimal/Char), 0 for any other instance — a datetime descriptor, a non-native byte order, a
copy made with the public constructors, or any descriptor of a non-legacy class (StringDType: NumPy's
getter reads the legacy fields slot, which a new-style descriptor does not have).
public int isbuiltin { get; }
Property Value
isnative
dtype.isnative (NumPy's PyArray_ISNBO): true unless the byte order is the host's OPPOSITE order —
so '=', '|' and an explicit host order ('<' on a little-endian machine) are all native.
public bool isnative { get; }
Property Value
metadata
dtype.metadata: the user metadata attached with np.dtype(..., metadata=...), or null when none
was (NumPy's None). Read-only, like NumPy's mappingproxy; an empty attachment is an empty
dictionary, not null. Metadata never takes part in equality, hashing, str or repr.
public IReadOnlyDictionary<string, object> metadata { get; }
Property Value
Remarks
Keys are strings (NumPy accepts any hashable key; string keys are what NumPy's own users attach — h5py's
'vlen', 'h5py_encoding'). A newbyteorder(string) or ensure_canonical(DType)
copy keeps it; promotion of non-parametric classes drops it (the result is the class singleton), as in NumPy.
na_object
dtype.na_object of a StringDType descriptor: the missing-data sentinel it was built with
(null is Python's None; a char sentinel reads back as a one-character
string). Use HasNAObject to test for it without the exception.
public object na_object { get; }
Property Value
Exceptions
- AttributeError
The descriptor has no missing-data object, or is not a
StringDType: NumPy's'numpy.dtypes.StringDType' object has no attribute 'na_object'.
names
dtype.names: always null (no structured dtypes).
public string[] names { get; }
Property Value
- string[]
ndim
dtype.ndim: the sub-array rank — always 0.
public int ndim { get; }
Property Value
num
NumPy's unique type number (dtype.num) as a raw int — exactly what NumPy's Python surface returns.
public int num { get; }
Property Value
shape
dtype.shape: the sub-array shape — always empty (no sub-array dtypes).
public int[] shape { get; }
Property Value
- int[]
str
The array-interface typestring (dtype.str): explicit byte order, kind and size — "<i4",
"|b1", ">f8", "<M8[ns]", "<m8", and for strings the CHARACTER count
("|S5" is 5 bytes, "<U5" is 5 code points = 20 bytes; the unsized forms are "|S0"/"<U0").
public string str { get; }
Property Value
subdtype
dtype.subdtype: always null (no sub-array dtypes).
public (DType, int[])? subdtype { get; }
Property Value
type_num
The same number as num, typed as NumPy's C NPY_TYPES enum — the NumPy-facing
dtype IDENTITY that rides alongside the storage/kernel discriminator typecode
(NPTypeCode). Byte-identical to np.dtype(...).num on the host it runs on, including
the platform-dependent integer resolution (on Windows/LLP64 int32.type_num is
NPY_LONG and int64.type_num is NPY_LONGLONG; on LP64
they are NPY_INT and NPY_LONG). NumSharp's two non-NumPy
dtypes report the user-range NUMSHARP_DECIMAL / NUMSHARP_CHAR.
public NPY_TYPES type_num { get; }
Property Value
Methods
Equals(DType)
Structural equality — NumPy's dtype.eq (PyArray_EquivTypes) for the descriptors NumSharp has:
the same class, the same byte order once '=' reads as the host's own order (so
np.dtype('f8').newbyteorder('<') equals np.dtype('f8') on a little-endian host while
>f8 does not), the same item size (U5 != U3) and the same instance parameters
(M8[ns] != M8[s]). The type character is NOT compared, as in NumPy: np.dtype('c') == np.dtype('S1').
Two StringDType descriptors are equal when they coerce alike and their missing-data objects are the same
missing value (NumPy's stringdtype_richcompare: StringDType(na_object=nan) == StringDType(na_object=np.nan)).
Metadata is ignored, as NumPy ignores it.
public bool Equals(DType other)
Parameters
otherDTypeThe descriptor to compare with; null is unequal.
Returns
- bool
True when both describe the same element layout and parameters.
Remarks
Two DIFFERENT NumPy numeric classes of one kind and one size are equal too, as in NumPy, whose cast between
them is no cast at all: np.dtype('g') == np.dtype('d') (long double is a 64-bit double in NumSharp),
and on Windows np.dtype(np.intc) == np.dtype(np.int32). NumSharp's own char and uint16 are not
(IsEquivalentNumeric(LegacyBuiltinDTypeMeta)).
One known difference: NumPy's relation folds exact metric-prefix units one way only (M8[1000ms] == M8[s]
but not the reverse); this equality is symmetric and keeps them apart. EquivTypes(DType, DType) is
NumPy's relation.
Equals(NPTypeCode)
Coercing equality with an NPTypeCode; Empty is unequal.
public bool Equals(NPTypeCode typecode)
Parameters
typecodeNPTypeCodeThe storage code.
Returns
- bool
True when the code's canonical descriptor equals this one.
Equals(object)
NumPy's coercing dtype.eq: the operand is converted to a descriptor first, so a
Type (typeof(int)), an NPTypeCode or a dtype string
("i4", "int32") compare equal to the descriptor they denote; anything that is not a dtype
(a bad string, a DTypeMeta class object, null) compares unequal without raising. A
StringDType descriptor does NOT coerce: its eq returns NotImplemented for anything but
another StringDType instance, so np.dtype('T') == 'T' and np.dtype('T') == str are False.
public override bool Equals(object obj)
Parameters
objobjectThe operand: a DType, a C# Type, an NPTypeCode or a dtype string.
Returns
- bool
True when
objdenotes an equal descriptor.
Remarks
NumPy reads None as float64 here too (np.dtype('f8') == None is True), and NumSharp's
converters do (np.dtype((DType)null) and np.result_type((DType)null) are float64), but equality
cannot: descr == null is how the engine tests for a missing descriptor, so null is unequal to every
descriptor by design.
Equals(string)
Coercing equality with a dtype STRING (np.dtype('i4') == 'i4'): an unparseable string is simply unequal
(np.dtype('i4') == 'garbage' is False, not an error). This overload exists because a string would
otherwise bind Equals(DType) through the implicit string→DType conversion, which
raises on a bad string.
public bool Equals(string dtype)
Parameters
dtypestringA NumPy dtype string; null or unparseable is unequal.
Returns
- bool
True when the string denotes an equal descriptor.
Equals(Type)
Coercing equality with a C# Type (np.dtype('i4') == np.int32); a non-NumSharp type is unequal.
public bool Equals(Type type)
Parameters
typeTypeThe C# element type; null or a non-NumSharp type is unequal.
Returns
- bool
True when
type's canonical descriptor equals this one.
From(NPTypeCode)
The descriptor of an NPTypeCode — the class's canonical instance. Every NumSharp API that takes a DType also takes an NPTypeCode through this conversion.
public static DType From(NPTypeCode typecode)
Parameters
typecodeNPTypeCodeA storage lane with a fixed element type.
Returns
- DType
The lane's descriptor.
Exceptions
- ArgumentException
typecodeis Empty.- NotSupportedException
typecodeis String: the text lane names no dtype (it holdsSandUarrays of every width andStringDTypearrays of every missing-value policy), so code that allocates "an array likea" bya.typecodewould silently get a one-character<U1and writea's wider elements past its end. Refusing here turns such an allocation — a route that took the lane where it needed the descriptor — into an error; a text route passesa.dtype, the full descriptor.
From(NPY_TYPES)
NumPy's PyArray_DescrFromType: the builtin descriptor for a NumPy type number — the reverse of
type_num. Every C-integer number has a class of its own, as in NumPy: on Windows
NPY_INT is intc (char 'i') beside NPY_LONG's
int32, on Linux NPY_LONGLONG is longlong (char 'q') beside
NPY_LONG's int64, so the returned descriptor's num is always the
number asked for. NPY_LONGDOUBLE / NPY_CLONGDOUBLE are NumSharp's
8 / 16-byte longdouble / clongdouble. Numbers with NO NumSharp class
(NPY_CFLOAT complex64, NPY_OBJECT, NPY_VOID,
the sentinels) are rejected, matching how the parser refuses a dtype NumSharp cannot represent.
public static DType From(NPY_TYPES type_num)
Parameters
type_numNPY_TYPESA NumPy type number.
Returns
- DType
The class's canonical instance (for the datetime pair, the generic-unit descriptor).
Exceptions
- NotSupportedException
NumSharp has no class of this number (complex64, object, void, or a sentinel).
From(string)
Builds a descriptor from a NumPy dtype string (NumPy's case-sensitive grammar). Same as dtype(string, bool, bool, IReadOnlyDictionary<string, object>).
public static DType From(string dtype)
Parameters
dtypestring
Returns
From(Type)
The descriptor of a C# Type — the class's canonical instance (np.dtype(typeof(int))).
public static DType From(Type type)
Parameters
typeType
Returns
GetHashCode()
Consistent with Equals(DType): the class and the canonical byte order — NumPy's
_array_descr_builtin hash, which reads '=' as the host's order too
(hash(np.dtype('f8').newbyteorder('<')) == hash(np.dtype('f8'))) and ignores the datetime unit
(hash(M8[ns]) == hash(M8[s])) — plus the item size for the flexible string classes (NumPy:
hash(U5) != hash(U10)). Fixed-size classes keep the two-field hash.
public override int GetHashCode()
Returns
- int
The hash code.
Remarks
A StringDType descriptor hashes its parameters (NumPy hashes the tuple (coerce, na_object)). A
NumPy numeric class hashes its kind and size instead of its type number, as NumPy's _array_descr_builtin
does ((kind, byteorder, flags, elsize, alignment)), so the equal descriptors of two equivalent classes
(hash(np.dtype('g')) == hash(np.dtype('d'))) hash alike.
GetTypeCode()
Returns this descriptor's NPTypeCode. Combined with a nullable DType
this keeps the old Type dtype idiom drop-in: dtype?.GetTypeCode() yields
NPTypeCode? (null for the none/infer state where dtype == null).
public NPTypeCode GetTypeCode()
Returns
Exceptions
- NotSupportedException
The class has no storage yet (a datetime64/timedelta64 descriptor in Stage A).
ToString()
NumPy's str(dtype): the name for a native descriptor (int32, datetime64[ns],
decimal), the typestring for a non-native or flexible one (>i4), and a StringDType
descriptor's own repr (StringDType(), StringDType(na_object=None)).
public override string ToString()
Returns
- string
The
str()text.
ToString(bool)
repr false: str(dtype). repr true: NumPy's repr(dtype) —
dtype('int32'), dtype('bool'), dtype('>i4'), dtype('<M8[ns]'), and for the
NumSharp-only user-range classes NumPy's unquoted user form dtype(decimal). A StringDType
descriptor prints the same text both ways, with no dtype(…) wrapper (StringDType(coerce=False)):
NumPy gives the class its own tp_repr and tp_str.
public string ToString(bool repr)
Parameters
reprboolTrue for
repr(dtype), false forstr(dtype).
Returns
- string
The text.
__getitem__(object)
Python's dtype[key]: a field lookup on a structured dtype. Every NumSharp descriptor is
non-structured, so every key raises NumPy's KeyError, whatever its type (dt[0],
dt['x'] and dt[None] all raise the same).
public DType __getitem__(object key)
Parameters
keyobjectThe field name or index NumPy would look up; never inspected.
Returns
- DType
Never returns.
Exceptions
- KeyError
Always — NumPy's
descr_subscripttext,There are no fields in dtype float64.(the dtype asstr(dtype)renders it:>f8,datetime64[ns]), quoted as Python'sstr(KeyError)shows it — the conventionnp.typename's KeyError follows too.
__len__()
Python's len(dtype): the number of FIELDS of a structured dtype — 0 for every NumSharp descriptor,
which is NumPy's answer for every non-structured dtype too (len(np.dtype('f8')) == 0). It is not the
item size; use itemsize for that.
public int __len__()
Returns
newbyteorder(string)
Return a new dtype with a different byte order — NumPy's dtype.newbyteorder
(PyArray_ByteorderConverter + PyArray_DescrNewByteorder), statement for statement.
public DType newbyteorder(string new_order = "S")
Parameters
new_orderstringThe byte order to force; only the FIRST character is read (
"little","lx"and"<"are one request).'S'/'s'(the default) swaps;'<'/'L'/'l'little-endian;'>'/'B'/'b'big-endian;'='/'N'/'n'native;'|'/'I'/'i'leaves the byte order as it is.
Returns
- DType
A NEW descriptor (never this one, never the class singleton:
isbuiltin == 0), keeping the unit and the metadata. A requested byte order is stored as given —'<'on a little-endian host stays an explicit'<'(native, equal to'=', butreprshowsdtype('<f8')); a swap of a native descriptor gives the opposite order and a swap of a non-native one gives the host's explicit order. A single-byte class keeps'|'whatever is requested.
Remarks
NumPy's new_order is a str: one signature since API-parity batch 6 (the char overload, a
NumSharp convenience Python has no counterpart for, is gone; write ">", not '>').
Exceptions
- TypeError
new_orderis null (NumPy'sbyteorder must be str, not NoneType); or the descriptor is of a non-legacy class (StringDType): NumPy'sCannot use DescrNewByteOrder for this new style DTypes., raised after the order itself is parsed.- ValueError
new_orderis empty or starts with another character (NumPy'sbyteorder not recognized (got 'X'), quoting the whole string).
Operators
operator ==(DType, DType)
Structural equality (null-safe).
public static bool operator ==(DType left, DType right)
Parameters
Returns
operator ==(DType, string)
NumPy's dtype == str: the string is converted to a descriptor and compared structurally, and a string
that is not a dtype compares UNEQUAL instead of raising (arraydescr_richcompare returns
NotImplemented when the conversion fails, so Python falls back to identity):
np.dtype('int32') == 'i4' is True, == 'bogus', == '' and == 'i4,i4' are False.
public static bool operator ==(DType left, string right)
Parameters
leftDTypeThe descriptor, or null.
rightstringA NumPy dtype string. A null string is the NULL DESCRIPTOR here, not a string (see the remarks).
Returns
- bool
True when both are null, or when
rightdenotes a descriptor equal toleft(Equals(string)).
Remarks
FOOTGUN this overload is built around: C# binds descr == null HERE, not to
==(DType, DType) — string is the better conversion target for a null literal, because an implicit
string → DType conversion exists and none the other way. descr == null is how the engine
tests for a missing descriptor, so a null string must answer exactly what a null descriptor answers: equal to
a null descriptor and to nothing else. Before this overload existed a string bound ==(DType, DType)
through that implicit conversion, which raises on a string that is not a dtype (parity QA-46). A
StringDType descriptor does not coerce (NumPy: np.dtype('T') == 'T' is False), as
Equals(object) answers.
operator ==(string, DType)
NumPy's reflected str == dtype (str.eq returns NotImplemented, so Python asks the
dtype): the same answer as operator ==(DType, string), with the operands swapped (it also
takes null == descr, which C# binds here for the same reason).
public static bool operator ==(string left, DType right)
Parameters
Returns
- bool
True when both are null, or when
leftdenotes a descriptor equal toright.
explicit operator Type(DType)
A descriptor converts back to its Type (none/null ⇒ null) — EXPLICITLY:
(Type)a.dtype, or the NumPy field a.dtype.type. It is deliberately not implicit, because
Type declares its own ==: with conversions in BOTH directions,
a.dtype == typeof(double) would be ambiguous between Type.== and DType.== (CS0034), and adding
==(DType, Type) overloads instead would make descr == null ambiguous (neither target is better). With
only the Type→DType direction implicit, a.dtype == typeof(double),
typeof(double) == a.dtype, Assert.AreEqual(typeof(double), a.dtype) (T infers as DType)
and a.dtype.Should().Be(typeof(double)) all resolve to the structural, coercing DType equality.
public static explicit operator Type(DType dtype)
Parameters
dtypeDType
Returns
Exceptions
- NotSupportedException
The class has no C# storage type yet (datetime64/timedelta64 in Stage A).
operator >(DType, DType)
NumPy's dtype > other: not equal, and right casts safely to left.
public static bool operator >(DType left, DType right)
Parameters
Returns
operator >=(DType, DType)
NumPy's dtype >= other: right casts safely to left.
public static bool operator >=(DType left, DType right)
Parameters
Returns
implicit operator NPTypeCode(DType)
A descriptor converts back to its NPTypeCode (none/null ⇒ Empty).
public static implicit operator NPTypeCode(DType dtype)
Parameters
dtypeDType
Returns
Exceptions
- NotSupportedException
The class has no storage yet (datetime64/timedelta64 in Stage A).
implicit operator DType(NPTypeCode)
An NPTypeCode converts to its canonical descriptor (Empty ⇒ none).
public static implicit operator DType(NPTypeCode typecode)
Parameters
typecodeNPTypeCode
Returns
implicit operator DType(NPY_TYPES)
A NumPy type number (NPY_TYPES) converts to its canonical descriptor — the fifth dtype
spelling, so np.zeros(3, NPY_TYPES.NPY_DOUBLE) binds the one DType overload like the others.
Delegates to From(NPY_TYPES), so a number with no NumSharp class on this platform
(e.g. NPY_CFLOAT) throws NotSupportedException — the same
throw-on-invalid the string conversion has (a bad "complex64" string). Unlike the reference-type
spellings there is no null case: NPY_TYPES is a value type, which is also
why it cannot meet the null-literal binding hazard that the ==(DType, string) operators answer
by reading a null string as the null descriptor. The reverse direction is the type_num property (not an operator, to keep
DType's back-conversions to Type/NPTypeCode unambiguous).
public static implicit operator DType(NPY_TYPES type_num)
Parameters
type_numNPY_TYPES
Returns
Exceptions
- NotSupportedException
The number has no NumSharp dtype class on the current platform.
implicit operator DType(NPTypeCode?)
A nullable NPTypeCode converts to a descriptor (null/Empty ⇒ none).
public static implicit operator DType(NPTypeCode? typecode)
Parameters
typecodeNPTypeCode?
Returns
implicit operator DType(string)
A NumPy dtype string converts to a descriptor via dtype(string, bool, bool, IReadOnlyDictionary<string, object>) — NumPy's exact,
case-sensitive spelling ("f4", "float32", "<f8", "M8[ns]"). null ⇒ none.
public static implicit operator DType(string dtype)
Parameters
dtypestring
Returns
implicit operator DType(Type)
public static implicit operator DType(Type type)
Parameters
typeType
Returns
operator !=(DType, DType)
Structural inequality (null-safe).
public static bool operator !=(DType left, DType right)
Parameters
Returns
operator !=(DType, string)
NumPy's dtype != str: the negation of operator ==(DType, string) (True for a
string that is not a dtype; a null string is the null descriptor).
public static bool operator !=(DType left, string right)
Parameters
Returns
- bool
False when both are null or when
rightdenotes an equal descriptor; True otherwise.
operator !=(string, DType)
NumPy's reflected str != dtype: the negation of operator ==(string, DType).
public static bool operator !=(string left, DType right)
Parameters
Returns
- bool
False when both are null or when
leftdenotes an equal descriptor; True otherwise.
operator <(DType, DType)
NumPy's dtype < other: strictly promotes — not equal, and left casts safely to right.
public static bool operator <(DType left, DType right)
Parameters
Returns
operator <=(DType, DType)
NumPy's dtype <= other: left casts safely to right.
public static bool operator <=(DType left, DType right)