Creating a Simple Random Number in .NET - c#

I need a simple random number for a loop that I am creating, and I can't for the life of me figure out what I am doing wrong here. Can someone look at the code below and explain to me why it's giving me the following errors:
Error 1 The best overloaded method match for 'System.Random.Next(int,
int)' has some invalid arguments
Error 2 Argument 1: cannot convert
from 'decimal' to 'int'
Error 3 Argument 2: cannot convert from
'decimal' to 'int'
I am trying to pull minimum and maximum values for the range from Numeric Up/Down controls. I would assume that LINQ or C# would have a simple, one line generator, but I can't find it.
Random rnd1 = new Random();
var integer = rnd1.Next(numericUpDown_RandomMin.Value,
numericUpDown_RandomMax.Value);
textbox.Text = integer.ToString();

NumericUpDown.Value returns a decimal, while Next() accepts an integer. You probably want to cast it to an integer first:
var integer = rnd1.Next((int)numericUpDown_RandomMin.Value, (int)numericUpDown_RandomMax.Value);

Well, first of all numericUpDown_RandomMin.Value and ..._RandomMax.Value are not int, so you might need to cast:
var integer = rnd1.Next((int)numericUpDown_RandomMin.Value, (int)numericUpDown_RandomMax.Value);
Other than that, what errors are you getting?

NumericUpDown is a decimal, you need to convert to an int.
var integer = rnd1.Next((int)numericUpDown_RandomMin.Value, (int)numericUpDown_RandomMax.Value);

Random.Next expects two Int32 values, but NumericUpDown.Value property is a decimal. Because conversion from decimal to int looses some value precision you have to do it explicitly :
rnd1.Next((int)numericUpDown_RandomMin.Value, (int)numericUpDown_RandomMax.Value);

Since NumericUpDown.Value's return type is Decimal, you need to explicitly convert your numericUpDown_RandomMin.Value and numericUpDown_RandomMax.Value values to Int32 because Random.Next(Int32, Int32) takes two parameter as Int32. Like;
Random rnd1 = new Random();
var integer = rnd1.Next((int)numericUpDown_RandomMin.Value, (int)numericUpDown_RandomMax.Value);
textbox.Text = integer.ToString();

Related

C# Cannot use Linq DefaultIfEmpty in ushort list items?

I want to take max value of ushort list and when that list is empty I want set "1" for default value.
For example:
List<ushort> takeMaxmumId = new List<ushort>();
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty(1).Max();
In my Example Visual Studio Show me this error:
'IEnumerable' does not contain a definition for
'DefaultIfEmpty' and the best extension method overload
'Queryable.DefaultIfEmpty(IQueryable, int)' requires a
receiver of type 'IQueryable'
When my list type were int I have not any problem, What is this problem in ushort type? And how can I fix this with best way?
The problem is that Select produces an IEnumerable<ushort>, while DefaultIfEmpty supplies an int default. Hence, the types do not match.
You can fix this by forcing ushort type on the default:
var max = takeMaxmumId.Select(x=>x).DefaultIfEmpty<ushort>(1).Max();
// ^^^^^^^^^^^^^
// This part can be removed
Demo.
You can also convert sequence elements to int:
var max = takeMaxmumId.Select(x => (int)x).DefaultIfEmpty(1).Max();
Since your data type is ushort you will have to staisfy the alternative orverload of DefaultIfEmpty extension method. i.e DefaultIfEmpty(this IEnumerable source, TSource defaultValue);
So you will have to cast to your source to type ushort.
var max = takeMaxmumId.Select(x => x).DefaultIfEmpty( (ushort) 1).Max();
You could try this one:
var max = takeMaximumId.DefaultIfEmpty((ushort)1).Select(x => x).Max();
The problem is due to the fact that passing 1 without the cast to ushort you can't apply the extension method DefaultIfEmpty, because 1 is interpreted as int and the list you want to apply this is of type List<ushort>. If you write the following
var max = takeMaximumId.DefaultIfEmpty(1).Select(x => x).Max();
you would get the error message below, which explains the above
statement:
'List' does not contain a definition for 'DefaultIfEmpty' and
the best extension method overload
'Queryable.DefaultIfEmpty(IQueryable, int)' requires a
receiver of type 'IQueryable'
As a side note, despite the fact that dasblinkenlight has already mentioned this in his post, you don't need at all the Select, since you don't make any projection there. You just want to get the maximum value of the numbers contained in your list.

Could someone explain line after line this code? And why i have an error: "Specified cast is not valid."? [duplicate]

I have the below function
public object Convert(object value)
{
string retVal = string.Empty;
int oneMillion = 1000000;
retVal = ((double)value / oneMillion).ToString("###,###,###.###");
return retVal;
}
I am invoking like
var result = Convert(107284403940);
Error: "Specified cast is not valid."
how to fix...
Note:~ the object value can be double, decimal, float, integer(32 and 64)..anything
Is it possible to do the typecasting at runtime?
Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)
Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))
If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).
instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

Cast number to type?

How do you go about casting numbers to specific data types?
Example:
253 is 32-bit signed integer
253L is 64-bit signed integer
253D is Double precision float
As you can see you can cast directly to Long and Double, but there are certain problems I have here. I cannot cast to byte, single, 16bit, unsigned...
It becomes a problem when I have to input data into many different functions with arguments of varying data types:
Method1( byte Value );
Method2( sbyte Value );
Method3( ushort Value );
//Etc.
Using int.Parse(string) or Convert.ToInt32 will do the trick.
Or you could try casting the value expicitly like that:
int age = 53;
Method1((byte) age);
Try using the Convert class:
http://msdn.microsoft.com/en-us/library/System.Convert_methods(v=vs.110).aspx
e.g.
int myInt = Convert.ToInt32(anything);

Error 1 Invalid expression term 'double'

private void buttonConvert_Click(object sender, EventArgs e)
{
//Convert number from C to F
double convertDecimal;
convertDecimal = 1.8;
textBoxF = double.Parse(textBoxC.Text) * double(convertDecimal) + 32;
^here is where I get the error
Error 1 Invalid expression term 'double'
I am pretty new to programming and but I just can't wrap my mind around trying to add, subtract, dividing, or multiplying numbers. I am trying to do a simple a simple conversion. Take the number from the Celsius textbox and convert it to Fahrenheit. I just don't understand the number part???
Thanks for your help!
double(convertDecimal) should be (double)convertDecimal
That looks like a C++ type-casting expression, which doesn't work in C#. And as convertDecimal already is of type double there's no need to cast it. Just use it directly:
textBoxF = double.Parse(textBoxC.Text) * convertDecimal + 32;
You only need to change the type of a variable (i.e. type-cast) when the variable is of a type not expected. Adding two double values is okay. Even adding a double and an int is okay because the integer is implicitly converted to a double.
Edit: You try to assign the result of the expression to a control, which will not work. You should convert the result to a string (e.g. with double.ToString), and then assign to the controls text field:
double farenheit = double.Parse(textBoxC.Text) * convertDecimal + 32;
textBoxF.Text = farenheit.ToString();

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);
}

Categories

Resources