Is it possible to create a new type in C #?

I want to create a new type, i.e. e:

[sbyte (1 Byte) Value-range : -128 to +127] [byte (1 Byte) Value-range : 0 to +255] [short (2 Byte) Value-range : -32768 to +32767] [ushort (2 Byte) Value-range : 0 to +65535] [int (4 Byte) Value-range : -2147483648 to +2147483647] [uint (4 Byte) Value-range : 0 to +4294967295] . . . etc. 

Now I want to create LInt (LowInt) Enter a range from 0 to 200000, so I do not want to use uint or int.

Is this possible with C #?

Thanks!

+4
source share
5 answers

This is not possible in different ways using a simple language, for example. int<5000,20000> .

Although this is possible with a more complex definition, it is not easy. It is hard to define and define all the semantics you want, for example:

  • Convert to other types of range
  • Convert from built-in numeric types
  • What should happen when overflow / underload
  • What should the resulting range of types do after arithmetic.

This solution will also not cover cases when you want one range of parameter types to be limited based on a different parameter value.

An alternative would be to use something like Code Contracts to define contracts for your code so that you can execute arbitrary static (compilation time).

Edit: Removed the link to SpecSharp. It looks like it has been replaced by code contracts ...

+2
source

Yes, what classes are for. Now you cannot create a new "built-in" type. The semantics may not be exactly the same, but I assume that you will still be interested in these differences.

+3
source

you can also use struct to create a "type", but you cannot create a primitive type.

0
source

You can create an object and process your conditions if you want it to act more like a primitive, trying to make it a structure

0
source

It's useless. Your processor architecture determines which pieces of data can be processed immediately and for what purposes. Even if you created a type that allows only different min-max values ​​(which you can implement when you overload the class and operator), it will not be more efficient in terms of memory or performance.

If you just want to apply some semantics, then something that should lead you to the right direction (it is by no means complete and does not contain support for verified and unverified keywords).

 struct MyInt { static uint max = 200000; readonly uint i; public MyInt(uint i) { this.i = i; } public static implicit operator MyInt(uint j) { if(j > max) throw new ArgumentException(); return new MyInt(j); } public static MyInt operator +(MyInt i, uint j) { try { return new MyInt(ii + j); } catch(ArgumentException) { throw new OverflowException(); } } public override string ToString () { return i.ToString(); } } 
0
source

All Articles