New C# programmer questions

C

CSharp-Jay

Hello all, I am new to C# and think I am finally starting to get it.
However, I have an issue right now that I believe is due to the fact
that I do not know how to close a Console application in code. You
would think its something like Console.Terminate or Quit or Close or
one of them, but that just isn't it, according to Visual Studio 2008.
As a result, my code jumps to my QuitGame() method, peels through it
nicely, then starts browsing around in a try/catch/finally statement I
have in my code for int parsing. After it gets done, it bombs out the
program. So I was hoping somebody could tell me how to kill my
Console application when the user wants to. Also, if anybody can tell
me how to link code files together so I can have multiple classes
rather than one class holding tons of methods, that would be kickin
lol. Visual Studio 2008 does not like the word include at all such as
(include Test or include Test.cs). It also does not like using Test
or using Test.cs, where Test.cs is the secondary code file. I already
added it to the project, it just gives me bunches of errors. Anyways,
I am rambling now, thanks all ahead of time :)

Jay
 
G

Göran Andersson

CSharp-Jay said:
Hello all, I am new to C# and think I am finally starting to get it.
However, I have an issue right now that I believe is due to the fact
that I do not know how to close a Console application in code. You
would think its something like Console.Terminate or Quit or Close or
one of them, but that just isn't it, according to Visual Studio 2008.
As a result, my code jumps to my QuitGame() method, peels through it
nicely, then starts browsing around in a try/catch/finally statement I
have in my code for int parsing. After it gets done, it bombs out the
program. So I was hoping somebody could tell me how to kill my
Console application when the user wants to.

Simple. You just exit out of the Main method.

You should find a well behaved way to return back to the Main method,
and exit the program the normal way.

If you try to quit the program from just anywhere, you will experience
what you have now. The code in the finally blocks will _always_ execute,
and there is no way around it (except forcing a stack overflow and crash
out of the program).
Also, if anybody can tell
me how to link code files together so I can have multiple classes
rather than one class holding tons of methods, that would be kickin
lol.

You just add the files in the project. Verify that the Build Action for
the file is Compile.
Visual Studio 2008 does not like the word include at all such as
(include Test or include Test.cs). It also does not like using Test
or using Test.cs, where Test.cs is the secondary code file. I already
added it to the project, it just gives me bunches of errors.

What you put in the using directive is the namespace of the class, not
the filename of the class.

If you create a new class file in the project, it will get the namespace
of the program by default, so it's instantly available in your code.
 
C

CSharp-Jay

Simple. You just exit out of the Main method.

You should find a well behaved way to return back to the Main method,
and exit the program the normal way.

If you try to quit the program from just anywhere, you will experience
what you have now. The code in the finally blocks will _always_ execute,
and there is no way around it (except forcing a stack overflow and crash
out of the program).


You just add the files in the project. Verify that the Build Action for
the file is Compile.


What you put in the using directive is the namespace of the class, not
the filename of the class.

If you create a new class file in the project, it will get the namespace
of the program by default, so it's instantly available in your code.

Okay so what line of code can be put in to return to Main then? See
my program is hopping back and forth between different methods and
classes now, but how to return to the main method I do not know. A
simple return; line does not seem to make the difference, the code
just continues to jump around. Thanks for all the help so far
though :)
 
P

Pavel Minaev

 Okay so what line of code can be put in to return to Main then?  See
my program is hopping back and forth between different methods and
classes now, but how to return to the main method I do not know.  A
simple return; line does not seem to make the difference, the code
just continues to jump around.  Thanks for all the help so far
though :)

Environment.Exit() should have the same effect as returning from
Main(), but can be called at any point of your program.

Note that it will still execute all finally blocks higher up the
stack.
 
C

CSharp-Jay

Without seeing the original code, it's impossible to say how to change it 
to do what you want.

Of course, no one wants to have to read through a complete program.  If 
you want an answer to your question, you should post a  
concise-but-complete code sample that effectively illustrates the basic  
structure of your program without including any of the ancillary code not 
immediately pertinent to the question.

With such an example, it should be straightforward to answer your question.

Pete

Okay uhm lets see. For example:

class Program
{
static void Main()
{
// do something
Program p = new Program(); // Visual Studio 2008 makes me create
an object to leave a static method for a non-static method?
p.MyMethod();
}

public void MyMethod()
{
// do more things
MyOtherMethod();
}

public void MyOtherMethod()
{
// do the last of the things, time to exit program...how to exit?
// Main(); <== does not work
}
}

How do you exit program...do you even need to return to Main()?
 
C

CSharp-Jay

Thank you for the example.  It makes it much easier to discuss code when  
we have code to discuss.  :)


No, you do not need to create the object.  You could have just made the 
methods you call "static" as well.  Since you didn't, then yes...you have  
to create an instance of the object in order to call the methods.




You just need to return from "MyOtherMethod()", and then return from  
"MyMethod()".

Given the code you posted, it should just work, since neither method makes  
any attempt at all to avoid returning.  If in your actual code you havea  
loop or some such, then you need to break out of the loop so that the  
method can return (this could be as simple as just putting a "return"  
statement inside the loop at the appropriate point).



Yes, that's my preferred way of doing it.  Pavel is not wrong to say that  
Environment.Exit() will terminate the program, but I prefer my programs to  
exit via the normal execution path.  In reality, either way is fine but 
it's my opinion that allowing the program to terminate forcefully  
introduces the possibility of unforeseen coding errors, inasmuch as it  
unstructures the code and one of the primary advantages to structured code  
is helping avoid certain kinds of coding errors.

Pete

Sweet this is helping a ton lol. Okay one last little bugged out
thing with the program. Take the following code example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main()
{
// Go to Input method to get user data
Input();

// Quit Program
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
return;
}

static void Input()
{
// Prompt the user for their hourly input
Console.WriteLine("Enter your hourly rate. (i.e. -
7.50)");

// Accept user input
string input = Console.ReadLine();

// Sanity check the code so we don't break
try
{
// Try to convert the user input to a double value
type
double.Parse(input);
}
catch
{
/* Invalid Input Option #1 - Display error message,
proceed to quit */
Console.Clear();
Console.WriteLine("Invalid input. Please restart the
program.");
Console.ReadKey();
return;

/* This is Invalid Input Option #2, having some issues
with values
* bugging out so for now its turned off.
Console.Clear();
Console.WriteLine("Invalid input. Please try
again.");
Console.ReadKey();
Input(); */
}

// Convert the user input to a double value type
double hourly = double.Parse(input);

// Pass the converted hourly rate to the Math Calculator
function
Calc.Math(hourly);
return;
}

public static void Display(double hourly, double daily, double
weekly, double monthly, double yearly)
{
// Display final output to user
Console.Clear();
Console.WriteLine("You stated that you make: ${0}
hourly.", hourly);
Console.WriteLine("On average you make:");
Console.Write("${0} Daily\n${1} Weekly\n${2} Monthly\n${3}
Yearly\n", daily, weekly, monthly, yearly);
Console.ReadKey();

// Return to main to quit
return;
}
}
}

I know it's long and for that I am sorry. The second class Calc and
method in that class Math has been left out to keep it short.
Basically, the code explains what the program does so it's not really
needed anyways. The problem is with that try/catch statement in here,
its the only one in the whole program. See the commented out bit in
the catch statement that I talk about being buggy? Well if you use
that option and for example you put in blank input, it will say
Invalid input. Please try again. Then it restarts the Input
function. Now if you put in a valid number like 7.50, the program
will crash. For the love of the gods I can't figure out why, I tried
stepping through my code and it just doesn't make sense. Does anybody
know the deal with this off the top of their head?

- Jay
 
G

Göran Andersson

CSharp-Jay said:
Okay so what line of code can be put in to return to Main then? See
my program is hopping back and forth between different methods and
classes now, but how to return to the main method I do not know. A
simple return; line does not seem to make the difference, the code
just continues to jump around. Thanks for all the help so far
though :)

You are not supposed to jump from one method to the next, that's not how
the program flow works. You call a method, the code in that method runs,
then the method ends and you return to the point where you called the
method.

If you keep calling methods within methods to create a program flow, you
will nest the calls deeper and deeper, and eventually just run out of
stack space, which causes an uncatchable exception and you program just
crashes.

You should have something like a main loop in your program, which makes
calls to the methods in your classes, and where you always return. To
exit the program you just end the main loop and return back to the Main
method.
 
C

CSharp-Jay

[...]
I know it's long and for that I am sorry.  The second class Calc and
method in that class Math has been left out to keep it short.

The sample looked fine to me.  It's seemed like just enough code to  
illustrate what you are talking about, without including extra code that  
wasn't relevant.

For what it's worth, you don't actually need a "return" statement at the  
end of a "void" method.  In case you were wondering about that.  :)
Basically, the code explains what the program does so it's not really
needed anyways.  The problem is with that try/catch statement in here,
its the only one in the whole program.  See the commented out bit in
the catch statement that I talk about being buggy?  Well if you use
that option and for example you put in blank input, it will say
Invalid input.  Please try again.  Then it restarts the Input
function.  Now if you put in a valid number like 7.50, the program
will crash.

Yes.  Because rather than looping within the Input() method until you have  
a valid value for the "input" string, you "recurse" into Input() again.  
Then when Input() returns from that second call, it's returning to the  
first call to Input().  The next thing that first call to Input() does  
after the second call returns to it is to try to execute the line that  
parses the input into the "hourly" variable.  But at that point it's using  
the previous, invalid value of the "input" string.

So the parse fails with an exception.

The fastest, easiest way to fix the code you posted is to just put a  
"return" statement after your call to Input().  However, IMHO there's  
really no reason to make the function recursive in the first place.  
Instead, try something like this:

     static void Input()
     {
         bool fValidInput = false;
         double hourly = 0;

         while (!fValidInput)
         {
             // Prompt the user for their hourly input
             Console.WriteLine("Enter your hourly rate. (i.e. - 7.50)");

             // Accept user input
             if (!(fValidInput = double.TryParse(Console.ReadLine(), out  
hourly)))
             {
                 Console.Clear();
                 Console.WriteLine("Invalid input.  Please try again.");
                 Console.ReadKey();
             }
         }

         // Pass the converted hourly rate to the Math Calculator function
         Calc.Math(hourly);
     }

Hope that helps.

Pete

Lol! Thanks so much, see my fu is weak lol. I still have yet to get
a bag of tricks like that and I didn't even know you write an if
statement like that. It is a confusing statement to be sure, as a
noob when you first look at it, it looks like it wouldn't even work or
make sense. But then again it does when you read it in plain text.
it starts out saying if (not true(fValidHourly = double.TryParse <--
returns true/false, perfect. Someday I hope to have such a bag of
tricks, thanks to everybody who posted here you were all such a great
help and really helped me to improve my coding skills by a large
amount. I have always enjoyed this group because the programmers here
are willing to help out and I am looking forward to the onslaught of
issues yet to come in my code thanks to this group. See you all next
time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top