Conditional Methods

One of, if not the most important concepts in software programming is that of Conditional Methods. Conditional methods provide a program with the ability to make decisions based on user input, user selections or data values. The code below is a simple example of a conditional method:

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
public static void Main(string[] args)
{
    Console.Write("Please enter any value: ");
 
    string enteredValue = Console.ReadLine();
 
    if (enteredValue.Length > 0)
    {
        Console.WriteLine("You entered: {0}", enteredValue);
    }
    else
    {
        Console.WriteLine("You didn't enter any value.");
    }
 
    Console.ReadLine();
}
[/sourcecode]

When run, it opens a console and requests the user to enter a value. It then checks to see if something was entered. Here is the condition… IF there was a value entered, display it ELSE notify the user that nothing was entered. In a more sophisticated software program the question or condition could be more complicated. Perhaps something like this:

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
public static void Main(string[] args)
{
    //add some logic to access a database to confirm you have
    //ample funds change the value to TRUE if we want to deliver
    //the dinero
    bool amountApproved = false;  
 
    Console.Write("Please enter amount to withdraw: ");
 
    string enteredValue = Console.ReadLine();
 
    if (enteredValue.Length > 0 && amountApproved)  
    {
        Console.WriteLine(
            "The amount entered: {0}, will be dispersed.", 
            enteredValue);
    }
    else
    {
        Console.WriteLine(
          "Sorry, the amount {0} exceeds your " + 
          "available credit.", 
          enteredValue);
    }
 
    Console.ReadLine();
}
[/sourcecode]

Although this is a basic concept, it needs to be understood, utilized and mastered before moving to more complex concepts.

Download the here.




Leave a Comment

Your email address will not be published.