Difference between Decimal and decimal

2019-02-16 05:27发布

If someone could explain to me the difference between Decimal and decimal in C# that would be great.

In a more general fashion, what is the difference between the lower-case structs like decimal, int, string and the upper case classes Decimal, Int32, String.

Is the only difference that the upper case classes also wrap functions (like Decimal.Divide())?

标签: c# class
5条回答
Emotional °昔
2楼-- · 2019-02-16 05:46

decimal, int, string are all just short hand notation to make things easier/prettier for you. The framework doesn't really know what a "decimal" is, but it does know System.Decimal, so when you compile your code, decimal just turns into System.Decimal. Try looking at some code where all the types are fully qualified, then try looking at some code where the aliases are used, I think most programmers will prefer the more compact aliases and perceive it as being easier to read. I also think it might be a throw back to C/C++ to make transitioning easier.

查看更多
We Are One
3楼-- · 2019-02-16 05:53

They are the same. The type decimal is an alias for System.Decimal.

So basically decimal is the same thing as Decimal. It's down to user's preference which one to use but most prefer to use int and string as they are easier to type and more familiar among C++ programmers.

查看更多
三岁会撩人
4楼-- · 2019-02-16 05:56

The built-in C# types aren't all structs*. They are aliases for the predefined types in the System namespace. They are literally the same in all ways except formatting. The alias types are lowercase and formatted like keywords (dark blue). The System types are PascalCased and formatted like types (light blue).


*object and string are classes

查看更多
该账号已被封号
5楼-- · 2019-02-16 05:57

Hadn't C# been case sensitive, some people would have written applications in all-caps as they did in Cobol and VB. This would have made it impossible for developers to read the code and maintain it. Case-sensitivity is a designer's effort to help making the language more usable.

查看更多
贪生不怕死
6楼-- · 2019-02-16 05:58

As C# is a .NET language, all types must map to a .NET Framework Type.

To answer your first question, decimal is an Alias of the System.Decimal .NET Framework type. They may be used interchangeably.

To answer your second question, both Decimal and decimal should extend the same functions, including both from the created variable and from the "Structure" of the value type itself.

decimal FirstDec = 12;
Decimal SecondDec = 13;
decimal ThirdDec = decimal.Ceiling(FirstDec, SecondDec);
Decimal FourthDec = Decimal.Floor(ThirdDec);
bool isEqual = FirstDec.Equals(SecondDec) && FourthDec.Equals(ThirdDec);

The following MSDN Page for Built-In Types will show you which System.ValueType each alias maps to. And for Decimal and decimal specifically, you can reference this MSDN Page for Decimal.

查看更多
登录 后发表回答