Which is the better way to instantiate a decimal? - c#

private decimal? _income;
public SomeClassName()
{
// First way
_income = new decimal(45000.75)
// Second way
_income = Convert.ToDecimal(45000.75)
}
Which of the above two instantiation is better? Why?

Just use a decimal literal:
_income=45000.75m;
If, on the other hand, you have a non-constant value that is currently a double, I'd probably just use:
_income = (decimal)doubleValue;
Unless or until I've got a demonstrable reason that it's incorrect.

Related

Convert and get maximum

I have an list of object which is have string "Value1" property and it is actually double.
So, I just want to get maximum and minimum values from my list with converting the property double.
That is my class.
public class Function
{
public int Id { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
I have a List<Function> and I need to get minimum "value1". Btw I am pretty sure about value1 can convertible to double. Is it possible to do this action in one line ?
What about simple casting?
myList.Max(x => double.Parse(x.Value1));
if you indeed want the min and the max, and you are sure the strings are all doubles:
string[] values = new[] { "1.1", "1.5", "2.654987" };
var doubles = values.Select(Convert.ToDouble);
var min = doubles.Min();
var max = doubles.Max();
LINQ can make it look nice
var sum = list.Select(item => item.Value1).Select(double.Parse).Sum();
You can pass a double.Parse function as parameter to the Select.
Notice that double.Parse will throw exception if Value1 is not valid double
It does matter whether you run your statement against database or not. if you do so and you do in one connection, so you will need to make all values in the same length as 'string' via a 'Select' statement and 'SqlFunctions.Replicate', and then 'Max' is going to work; but if your value contains decimals you will have trouble. Another way to escape from this solution is to fetch all value into memory using 'ToList' for instance; after that cast 'string' value to 'double' to get 'Max' statement working. but the downside is that all values is fetched into memory once

Converting from `NSDecimal` or `NSDecimalNumber` to C#'s `decimal` type

I've got an NSDecimalNumber from StoreKit's SKProduct class, and I want to convert it to C#'s decimal type to minimize loss of precision. Is there a straightforward way to do such a thing?
I figure my two choices are:
Assume that I understand the binary implementation of each and do my own bit-wise conversion, or
Have NSDecimalNumber give me a string and then have decimal parse it.
I figure option 1 is way too much work and probably even brittle, so I'm inclined to go with option 2. But that doesn't seem like the best I can do, either. (I can live with how slow it'll be, because it happens exceptionally rarely.
NSDecimal and NSDecimalNumber structures representation are not identical to .NET System.Decimal.
Conversion is always possible but not easy. If performance is not a huge matter then you'll best served by using the string representation to convert between them.
Just because this tripped me up and cost me quite some time here's a couple extension methods I now use for conversion between NSDecimal and decimal. This was quite frustrating and I am surprised there is no better way built in.
public static class NumberHelper
{
public static decimal ToDecimal(this NSDecimal number)
{
var stringRepresentation = new NSDecimalNumber (number).ToString ();
return decimal.Parse(stringRepresentation, CultureInfo.InvariantCulture);
}
public static NSDecimal ToNSDecimal(this decimal number)
{
return new NSDecimalNumber(number.ToString(CultureInfo.InvariantCulture)).NSDecimalValue;
}
}
Since Xamarin iOS SDK 12, operators are available for explicitly converting an NSDecimal to a decimal and implicitly converting a decimal to an NSDecimal.
Using these operators, you can take the following code as an example for achieving your goal:
var nsDecimalNumber = new NSDecimalNumber("128.478", new NSLocale("en-US"));
var nsDecimal = nsDecimalNumber.NSDecimalValue;
var csharpDecimal = (decimal)nsDecimal;
var nsDecimalAfterConversion = (NSDecimal)csharpDecimal;
var nsDecimalNumberAfterConversion = new NSDecimalNumber(nsDecimalAfterConversion);

Error: Specified cast is not valid while converting decimal to double

I have a function as under
private double RoundOff(object value)
{
return Math.Round((double)value, 2);
}
And I am invoking it as under
decimal dec = 32.464762931906M;
var res = RoundOff(dec);
I am gettingthe below error
Specified cast is not valid
What is the mistake?
Thanks
Casting the object to double will attempt to unbox the object as a double, but the boxed object is a decimal. You need to convert it to a double after first unboxing it. Then you perform the rounding:
Math.Round((double)(decimal)value, 2);
The other answers are correct in terms of getting something that will run - but I wouldn't recommend using them.
You should almost never convert between decimal and double. If you want to use a decimal, you should use Math.Round(decimal). Don't convert a decimal to double and round that - there could easily be nasty situations where that loses information.
Pick the right representation and stick with it. Oh, and redesign RoundOff to not take object. By all means have one overload for double and one for decimal, but give them appropriate parameter types.
As an alternative to John's answer, if you want to use other number types than just decimal, you could use this code;
private double RoundOff(object value)
{
return Math.Round(Convert.ToDouble(value), 2);
}

C# enum to string auto-conversion?

Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time. Here's an example of what I'd like to do:
enum Rank { A, B, C }
Rank myRank = Rank.A;
string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string'
string myString2 = Rank.A.ToString(); // OK: but is extra work
No. An enum is its own type, so if you want to convert it to something else, you have to do some work.
However, depending on what you're doing with it, some methods will call ToString() on it automatically for you. For example, you can do:
Console.Writeline(Rank.A);
You are not probably looking for enums itself, but a list of string constant. It can fit your needs better in some scenarios.
Use this instead:
public static class Rank
{
public const string A = "A";
public const string B = "B";
public const string C = "C";
}
No, but at least you can do things with enums that will call their ToString() methods when you might need to use their string value, e.g.:
Console.WriteLine(Rank.A); //prints "A".
The correct syntax should be
myRank.ToString("F");
[Caution, hack] Unsure as to whether this is nasty, to me it seems a reasonable compromise.
var myEnumAsString = MyEnum+"";
Console.WriteLine(myEnumAsString); //MyEnum
This will force implicit ToString()

What's a great way to convert a string to a number in C#?

I'm familiar with:
Convert.ToInt32(texthere);
But is there another cleaner way to do it? I like having readable code for coworkers and I'm always on the lookout for anything that'll make my work seem more obvious.
What's not obvious about Convert.ToInt32 ?
Convert this value To an Int32 ?
You can also use Parse and TryParse methods of int, double, float and decimal types.
int.TryParse / double.TryParse
Int.parse, float.parse and so forth.
Personally I would use the standard methods stated (Convert.ToInt32, double.TryParse etc), but if you want an alternative ...
You could add an extension method, something like this (not tested it):
public static class Extensions
{
public static int ConvertStringToInt(this string s)
{
return Convert.ToInt32(s);
}
public static long ConvertStringToLong(this string s)
{
return Convert.ToInt64(s);
}
}
And then you could:
string test = "1234";
int testToInt = test.ConvertStringToInt();
long testToLong = test.ConvertStringToLong();

Categories

Resources