How do I create my own primitive? For example an integer that has a range of to 1-10.
EDIT: This came from a task on Rosetta Code.
Defining Primitive Data Types: Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10.
I added it here because I thought it might be useful to others.
How can primitive types be "written" in any programming language? You can write operations on them, but you cannot write the types themselves, that's why they are primitive.
The language defines eight Java primitive data types: boolean, float, double, byte, short, int, long and char. These eight Java primitive data types fall into the category of things that aren't objects. In a Java program, data always manifests itself as one of the eight primitive data types.
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.
Primitive data types are number, string, boolean, NULL, Infinity and symbol.
Ok, lets see. First off, there are some datatypes build into the CLR. Those cannot be modified or new ones added, since they are part of the standard. You can find a list here or here. That's C#, but the list should also exist for VB.net somewhere, and it should look equal because the underlying CLR is the same. Also, the list is not complete because floats and char are missing, but you get the idea.
But then, there are some structs that encapsulate those Data Types and add some Extra functionality. For example, System.Int32 is just a plain standard struct, no magic involved. Feel free to look at it in Reflector, it's in mscorlib:
[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
So you want your own "1 to 10" Integer? Then I recommend looking at the nearest suitable type, which is either Int16
or Byte
. If you look at them, you can see that they all look somewhat similar, but that they are based on one of the built-in datatypes.
Just copy/pasting and modifying some of the built-in structs (i.e. System.Byte
) does not completely work because some members are internal (i.e. NumberFormatInfo.ValidateParseStyleInteger
), but Reflector could help here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With