nested conversion question (C#) - c#

Hey, I am working on a school project and a line of code I just wrote kind of made me laugh and think to myself, "There must be a better way to do what I just did". So, my question is, is this really the best way to do this? It seems kind of silly. BTW, size is an int that is passed to this function.
int tiles = Convert.ToInt32(Math.Sqrt(Convert.ToDouble(size)));
I know this works, but is there a better way?

Since int is implicitly convertable to double, you can leave out the inner conversion:
int tiles = Convert.ToInt32(Math.Sqrt(size));
That being said, Convert.ToInt32 is overkill in this situation. You can also just use a simple cast, since you know it's going from double to int:
int tiles = (int)Math.Sqrt(size);

Related

C# user int array declaration

I am having issues with c# (new to it) but with some programming experience (not great, many moons ago, Python)
I must be doing something wrong and looking for the answer incorrect, spent a couple of days searching for this. I think its really simple and I must be doing something wrong.
Basically I want to take a user input of an interger and store it as an array so I perform maths on individual numbers. However, when I try and get the console to read the number I can not then access the 4th position etc because as c# keeps telling me.
Cannot apply indexing with [] to an expression of type int
what elemental mistake am I making here guys,
Edited to improve original question.
sorry all, that was a little vague. Let me show you how my idea works in python and maybe that would help matters. Basically, i'm trying to access the positions of an integer.
Number = (input("Please enter a Number number"))
check_digit = number[7]
loyalty = number[:-1]
I want the user to enter the number and then the program access different numbers in the array.
Judging from the exception, you probably declare you Array like this:
int myArray;
Instead of this:
int[] myArray;
Error 1 Cannot apply indexing with [] to an expression of type 'int'

Why int.Parse(NumericUpDown.Value.ToString())?

I've run into this pattern repeatedly in a project I'm working with:
int myIntValue = int.Parse(myNumericUpDown.Value.ToString());
This seems a little bit bananas to me, get a string from a decimal and then parse the string to get an int, and I wonder if there is something I'm missing that necessitates it. Seems like it has to be deliberate. Is there a reason that should be used rather than the obvious approach:
int myIntValue = (int)myNumericUpDown.Value;
Or:
int myIntValue = Convert.ToInt32(myNumericUpDown.Value);
Of course we cannot look into the mind of the programmer who wrote that code initially, but doing numeric conversions through strings is quite common with newer programmers. Presumably they first wrote
int myIntValue = myNumericUpDown.Value
got a compiler error, found Int32.Parse and put the pieces together.
There is really no reason at all to convert it to a string first, and then parse an integer from that - if anything it is inefficient and awkward to read.
In fact note that if for whatever reason the ToString gives an actual decimal number (like 3.0 instead of 3) the code will throw a System.FormatException which is not caught. From the assumption that you are not seeing that exception when running, I deduce that the control is set such that the Value property is always an integer, never something like 1.932, hence I would argue that the fastest way to get it as an integer is a hard cast
int myIntValue = (int)myNumericUpDown.Value;
(and add a try/catch for the inevitable case that your form designer messes up and sets the initial value of the control to 0.5).

Retrieving the highest number in an array recursively in C#?

How can I retrieve the highest number in an array recursively in C#?
Right now you're probably thinking that we're mean for not giving you the answer -- and I admit that I have the answer written down and part of me wants to give it to you, even.
Programming is all about finding the solutions to problems yourself. When you're hired as a programmer, you may have other people to lean on, but they've all got their own problems, and you'll need to be able to pull your own weight.
Recursion (in an oversimplifed answer) means to call the same operation over and over until the result is produced. That means you need in every recursive operation, you need to know (at least) two things:
What you're looking for
What you've found so far
The 'What you're looking for' is the termination condition. Once you find that, all work can stop and you can go home.
The 'what you've found so far' is how you know what've you've checked so you don't retread old ground.
So what do you need to know in order to find the highest value in an array recursively?
The contents of the Array.
The highest number you've found so far.
Have you already looked at this part of the Array? (Why look through it again?)
That would produce a method signature that looks like:
public int GetHighestNumber(int[] array, int highestNumberFound, int lastIndexChecked);
Once you're inside the array, you've got to do the following:
Iterate through the array
Stop when you find a value that is higher than the highestNumberFound
Call GetHighestNumber again with the new highestNumberFound and lastIndexChecked updated.
When there are no more 'higher' numbers, then return the highest number found.
I realize it sounds trite, but learning this stuff on your own will make you a better programmer.
If you want to be a professional programmer, you have got to learn this stuff on your own.
If you don't want to be a professional programmer, then drop the course and do something you love.
Here's just a hint (taking int[] as an example):
public int FindMax(int[] array, int indexSoFar, int maxSoFar)
Think about:
The start conditions
The termination conditions
How you move through the array recursively
Reason of EDIT: Didnt want to spoil the answere.
Greetings.

Is there any plugin for VS or program to show type and value etc... of a C# code selection?

What I want to do is be told the type, value (if there is one at compile-time) and other information (I do not know what I need now) of a selection of an expression.
For example, if I have an expression like
int i = unchecked((short)0xFF);
selecting 0xFF will give me (Int32, 255), while selecting ((short)0xFF) will give me (Int16, 255), and selecting i will give me (Int32, 255).
Reason why I want such a feature is to be able to verify my assumptions. It's pretty easy to assume that 0xFF is a byte but it is actually an int. I could of course refer to the C# Language Specifications all the time, but I think it's inefficient to have to refer to it everytime I want to check something out. I could also use something like ANTLR but the learning curve is high.
I do intend to read the entire specs and learn ANTLR and about compilers, but that's for later. Right now I wish to have tools to help me get the job done quickly and accurately.
Another case in point:
int? i = 0x10;
int? j = null;
int x;
x = (i >> 4) ?? -1;//x=1
x = (j >> 4) ?? -1;//x=-1
It may seem easy to you or even natural for the bottom two lines in the code above. (Maybe one should avoid code like these, but that's another story) However, what msdn says about the null-coalescing operator is lacking information to tell me that the above code ((i>>4)??) is legal (yet it is, and it is). I had to dig into grammar in the specs to know what's happening:
null-coalescing-expression
conditional-or-expression
conditional-and-expression
exclusive-or-expression
and-expression
equality-expression
relational-expression
shift-expression
shift-expression right-shift additive-expression
... (and more)
Only after reading so much can I get a satisfactory confirmation that it is valid code and does what I think it does. There should be a much simpler way for the average programmer to verify (not about validity, but whether it behaves as thought or not, and also to satisfy my curiosity) such code without having to dive into that canonical manual. It doesn't necessary have to be a VS plugin. Any alternative that is intuitive to use will do just as well.
Well, I'm not aware of any add-ins that do what you describe - however, there is a trick you can use figure out the type of an expression (but not the compile-time value):
Assign the expression to a var variable, and hover your mouse over the keyword var.
So for example, when you write:
var i = unchecked((short)0xFF);
and then hover your mouse over the keyword var, you get a tooltip that says something like:
Struct System.Int16
Represents a 16-bit signed integer.
This is definitely a bit awkward - since you have to potentially change code to make it work. But in a pinch, it let's you get the compiler to figure out the type of an expression for you.
Keep in mind, this approach doesn't really help you once you start throwing casts into the picture. For instance:
object a = 0xFF;
var z = (string)a; // compiles but fails at runtime!
In the example above, the IDE will dutifully report that the type of var z is System.String - but this is, of course, entirely wrong.
Your question is a little vague on what you are looking for, so I don't know if "improved" intellisense solves it, but I would try the Productivity Power Tools.

Comparing Doubles in Visual Studio - a standard way to catch this?

Even experienced programmers write C# code like this sometimes:
double x = 2.5;
double y = 3;
if (x + 0.5 == 3) {
// this will never be executed
}
Basically, it's common knowledge that two doubles (or floats) can never be precisely equal to each other, because of the way the computer handles floating point arithmetic.
The problem is, everyone sort-of knows this, but code like this is still all over the place. It's just so easy to overlook.
Questions for you:
How have you dealt with this in your development organization?
Is this such a common thing that the compiler should be checking that we all should be screaming really loud for VS2010 to include a compile-time warning if someone is comparing two doubles/floats?
UPDATE: Folks, thanks for the comments. I want to clarify that I most certainly understand that the code above is incorrect. Yes, you never want to == compare doubles and floats. Instead, you should use epsilon-based comparison. That's obvious. The real question here is "how do you pinpoint the problem", not "how do you solve the technical issue".
Floating point values certainly can be equal to each other, and in the case you've given they always will be equal. You should almost never compare for equality using equals, but you do need to understand why - and why the example you've shown isn't appropriate.
I don't think it's something the compiler should necessarily warn about, but you may want to see whether it's something FxCop can pick up on. I can't see it in the warning list, but it may be there somewhere...
Personally I'm reasonably confident that competent developers would be able to spot this in code review, but that does rely on you having a code review in place to start with. It also relies on your developers knowing when to use double and when to use decimal, which is something I've found often isn't the case...
static int _yes = 0;
static int _no = 0;
static void Main(string[] args)
{
for (int i = 0; i < 1000000; i++)
{
double x = 1;
double y = 2;
if (y - 1 == x)
{
_yes++;
}
else
{
_no++;
}
}
Console.WriteLine("Yes: " + _yes);
Console.WriteLine("No: " + _no);
Console.Read();
}
Output
Yes: 1000000
No: 0
In our organization we have a lot of financial calculations and we don't use float and double for such tasks. We use Decimal in .NET, BigDecimal in Java and Numeric in MSSQL to escape round-off errors.
This article describes the problem: What Every CS Should Know About floating-Point Arithmetic
If FxCop or similar (as Jon suggests) doesn't work out for you a more heavy handed approach might be to take a copy of the code - replace all instances of float or double with a class you've written that's somewhat similar to System.Double, except that you overload the == operator to generate a warning!
I don't know if this is feasible in practice as I've not tried it - but let us know if you do try :-)
Mono's Gendarme is an FxCop-like tool. It has a rule called AvoidFloatingPointEqualityRule under the Correctness category. You could try it to find instances of this error in your code. I haven't used it, but it should analyse regular .net dll's. The FxCop rule with the same name was removed long ago.

Categories

Resources