Which type should I use in C# to represent numbers?

-

Yesterday I found an old email in my mail box that I thought might be gen­er­ally in­ter­est­ing.

I was ask­ing the tech­ni­cal lead on the C# com­piler which al­go­rithm/​short­cut peo­ple should use to choose their number types’ among the many avail­able in the lan­guage. I was ask­ing for some­thing that works the ma­jor­ity of times, even if not al­ways. I’m sure there are other sce­nar­ios we haven’t con­sider. Anyhow, here is his al­go­rithm.

If you need frac­tions:

Otherwise:

Byte, sbyte, short, ushort, uint, and ulong should only ever be used for in­terop with C code. Otherwise they’re not worth the has­sle.

Tags

12 Comments

Comments

Cory Nelson

2007-02-27T18:29:35Z

i re­ally mean this in the nicest way: if you get con­fused by un­signed types, stop cod­ing.  maybe the tech­ni­cal lead needs to have more faith in the com­pe­tency of the de­vel­op­ers he is tar­get­ing.

Yeah, but in the .NET frame­work un­signed types are not CLR com­pli­ant, which you might or might not be wor­ried about.

Fabrice's weblog

2007-02-27T19:24:05Z

Luca Bolognese, from the Microsoft C# team, has an in­ter­est­ing post that aims at pro­vid­ing an­swers to

but if you use what the value means, is­n’t it more  readable ?
I mean if you have a file header
with a uin­t32 fourcc then a uin­t16 ver­sion value, its more read­able since you know what you should look for. if you use int fourcc and int ver­sion i don”t know how the bytes map in the file.

Eber Irigoyen

2007-02-27T20:59:12Z

but this ap­plies to the whole CTS, not just C#… right?

.NET a 2.860 m de altura

2007-02-28T22:57:25Z

C# nos ofrece var­ios tipos de datos para rep­re­sen­tar n&ua­cute;meros y, so­bretodo para quienes est&aa­cute;n

There Must Be Some Mistake

2007-03-01T20:54:07Z

Saw this post to­day de­scrib­ing ba­sic guid­ance for when to use the dif­fer­ent nu­meric data types avail­able

Charlie Calvert's Community Bl

2007-03-02T03:23:24Z

Welcome to the twenty-sec­ond Community Convergence, the March CTP is­sue. I’m Charlie Calvert, the C#

Welcome to the twenty-sec­ond Community Convergence, the March CTP is­sue. I&#039m Charlie Calvert, the

Ronaldo Ferreira

2007-03-02T18:36:41Z

I coded these days a method that reads a bi­nary file, but all data were rep­re­sented with only two bytes (an ushort is enough). I re­ally do not see the rea­son to forget” these types. If I have coded this same method with int, I have had throw away a lot of bytes.

>I have had throw away a lot of bytes.
in­ter­naly it maybe have been casted as int any­way by the com­pi­la­tor

I want to write a Matrix (Math) with gener­ics that can in­stance it with all num­bers(float, dou­ble, int,…).
any idea?
I think it is im­posi­ble.
[imposible says i am posi­ble :) ]