简体   繁体   中英

Initialising a System.Decimal v Initialisting a decimal data type

I am use to using the decimal data type like this:

decimal Cost = 30M;

This initialises the decimal with £30 (£ is in the context of my application). I am planning to use a type alias for Decimal in my application like this:

using Cost = System.Decimal

I believe I have to use the object rather than the primitive type when using a type alias. Please let me know if that is not correct?

Also I have noticed that I cannot do this:

Decimal cost = new Decimal(30M);

I have to do this instead:

Decimal cost = new Decimal(30);

Is the initialisation code above suitable for a currency?

This initialises the decimal with £30 (£ is in the context of my application). I am planning to use a type alias for Decimal in my application like this: using Cost = System.Decimal

Ok, thats a valid option.

I believe I have to use the object rather than the primitive type when using a type alias. Please let me know if that is not correct?

I'm not sure what you are asking, but if you are using a type alias, the whole idea is to use it:

var cost = new Cost(10);

Rememnber, a type alias is a type alias; wherever you can System.Decimal , Cost is valid too.

Also I have noticed that I cannot do this: Decimal cost = new Decimal(30M);

Yup, and you can't do Cost cost = new Cost(30M); either, because decimal doesn't define such constructor overload. The reason being, if you already have a Decimal / Cost in hand why in the world would you want to new it up again? Cost cost = 30M; would do just fine.

Also notice that Cost cost = 30; is just fine too, the compiler will perform the implicit conversion for you.

  1. Yes, you need to use the fully qualified type name to use an alias. From the docs :

    Create a using alias to make it easier to qualify an identifier to a namespace or type. The right side of a using alias directive must always be a fully-qualified type regardless of the using directives that come before it.

    It's worth noting that using a type alias is very uncommon, particularly when using a built in value type like decimal . I would not recommend that you do that.

  2. You can't do new Decimal(30M) because the type doesn't have a constructor that takes a decimal, after all it would be pointless because you can simply do this (where the M qualifier is optional):

     Decimal cost = 30M; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM