Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I create my own primitive data type in .NET?

Tags:

.net

vb.net

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.

like image 406
Jonathan Allen Avatar asked Dec 25 '08 18:12

Jonathan Allen


People also ask

Can programmers write their own primitive data types?

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.

Can we create object for primitive data type?

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.

What makes a primitive data type?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.

What are the 7 primitive data types?

Primitive data types are number, string, boolean, NULL, Infinity and symbol.


1 Answers

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.

like image 95
Michael Stum Avatar answered Sep 21 '22 16:09

Michael Stum