Fundamentals of Strings

Introduction

As we have seen so far, a string is one or a group of characters. Based on this, to get a string, you can create a group of characters and include them in double-quotes.

To support strings, the .NET Framework provides a class named String. This class is defined in the C# language as the string data type.

A String Variable

To create a string, you can declare a variable of type string or String. You can also use the dynamic keyword to declare the variable. Here are examples:

string firstName;
dynamic lastName;

You can also use the var keyword to declare a string variable. In this case, you must initialize the variable.

Practical LearningPractical Learning: Introducing Characters

Strings and Functions

As we saw in previous lessons, you can create a function that produces a string value. You can pass a string parameter to a function.

An Empty String

A string is referred to as empty if it contains no characters at all. To create such a string, you can declare a string or String variable and initialize it with empty double-quotes. Here is an example:

string empty = "";

To support the ability to create an empty string, the String class is equipped with a static field named Empty:

public static readonly string Empty

The String.Empty field allows you to initialize a string variable with an empty space or to reset a string to an empty value. Here are examples:

string firstName = string.Empty;
var middleName = string.Empty;
dynamic lastName = string.Empty;

Converting a Value or an Object to a String

To allow you to convert any value or object to a string, the object data type (that is, its equivalent Object class) is equipped with a method named ToString Most classes override this method. If you want a particular implementation of this method for your class, you must override it.

The Length of a String

The length of a string, also referred to as its size, is the number of symbols or characters it contains. To let you get this information, The String class is equipped with a property named Length. Here is an example of using it:

string gender = "Female";

WriteLine("{0} contains {1} characters", gender, gender.Length);

WriteLine("===============================");

This would produce:

Female contains 6 characters
===============================
Press any key to continue . . .

Practical LearningPractical Learning: Introducing the Number of Characters

  1. In the Solution Explorer, right-click Program -> Rename
  2. Type AccountValidation (to get AccountValidation.cs) and press Enter
  3. Read the message box and click Yes
  4. Change the document as follows:
    using static System.Console;
    
    Write("New Password: ");
    string strNewPassword = ReadLine()!;
    int length = strNewPassword.Length;
    
    WriteLine("Your password contains {0} characters.", length);
    WriteLine("=====================================");
  5. To execute the project, on the main menu, click Debug -Start Without Debugging
  6. When requested, type the New Password as password and press Enter
    New Password: password
    Your password contains 8 characters.
    =====================================
    
    Press any key to close this window . . .
  7. Close the window and return to your programming environment
  8. From what we learned about characters in the previous lesson, change the code as follows:
    using static System.Console;
    
    int digits = 0, symbols = 0, lowercase = 0, uppercase = 0;
    
    Write("New Password: ");
    string strNewPassword = ReadLine()!;
    int length = strNewPassword.Length;
    
    for (int i = 0; i < length; i++)
    {
        if (Char.IsDigit(strNewPassword[i]))
            digits++;
    
        if (Char.IsSymbol(strNewPassword[i]) || Char.IsPunctuation(strNewPassword[i]))
            symbols++;
    
        if (Char.IsLower(strNewPassword[i]))
            lowercase++;
    
        if (Char.IsUpper(strNewPassword[i]))
            uppercase++;
    }
    
    WriteLine("=====================================");
    WriteLine("Password Analysis");
    WriteLine("-------------------------------------");
    WriteLine("Digits:            {0}", digits);
    WriteLine("Symbols:           {0}", symbols);
    WriteLine("Lowercase Letters: {0}", lowercase);
    WriteLine("Uppercase Letters: {0}", uppercase);
    WriteLine("-------------------------------------");
    WriteLine("Characters:        {0}", length);
    WriteLine("=====================================");
  9. To execute the project, on the main menu, click Debug -> Start Without Debugging
  10. When requested, type the New Password as $0uthD@koTA1889 and press Enter:
    New Password: $0uthD@koTA1889
    =====================================
    Password Analysis
    -------------------------------------
    Digits:            5
    Symbols:           2
    Lowercase Letters: 5
    Uppercase Letters: 3
    -------------------------------------
    Characters:        15
    =====================================
    
    Press any key to close this window . . .
  11. Close the window and return to your programming environment

The Nullity of a String

A Null String

A string is referred to as null if it doesn't (yet) have a(ny) character(s)s. This is usually the case when the string has just been created, or a string variable has just been declared. When you have just declared a variable, to indicate that it is null, assign the null keyword to it. The variable must be declared using the string data type, the String class, or the dynamic keyword. Here are example:

string firstName = null;
dynamic lastName = null;
String homeAddress = null;

If you decide to use the var keyword to declare the variable, you cannot assign null to it.

A Null or Empty String

A string is referred to as null if it has lost its character(s). To let you find out whether a string is empty or null, the String class is equipped with a static method named IsNullOrEmpty. Its syntax is:

public static bool IsNullOrEmpty(string value)

Practical LearningPractical Learning: Setting an Empty String

  1. Change the code as follows:
    using static System.Console;
    
    string strNewPassword = string.Empty;
    
    Write("New Password: ");
    
    strNewPassword = ReadLine()!;
    
    if (string.IsNullOrEmpty(strNewPassword))
    {
        WriteLine("You cannot have a null or empty password. You must provide " +
                  "a valid password.");
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. When requested, for the New Password, simply press Enter:
    New Password:
    You cannot have a null or empty password. You must provide a valid password.
    
    Press any key to close this window . . .
  4. Close the window and return to your programming environment

A String With a White Space

A string contains a white space if it was previously initialized with at least one character and all its characters have been removed or the string was simply initialized with something like the Space bar of the keyboard. Here is an example:

string whiteSpace = "    ";

A Null, Empty, or White-Spaced String

To let you find out whether a string is null or contains a white space, the String class is equipped with a static method named IsNullOrWhiteSpace. Its syntax is:

public static bool IsNullOrWhiteSpace(string value)

Practical LearningPractical Learning: Checking a Text-Based Control

  1. Change the document as follows:
    using static System.Console;
    
    string strNewPassword = string.Empty;
    int digits = 0, symbols = 0, lowercase = 0, uppercase = 0;
    
    Write("New Password: ");
    
    strNewPassword = ReadLine()!;
    
    if (string.IsNullOrWhiteSpace(strNewPassword))
    {
        WriteLine("You cannot have a null or white space password (a password with no character at all). " +
                  "You must create a new password that conforms to this company's password rules.");
    }
    
    int length = strNewPassword.Length;
    
    for (int i = 0; i < length; i++)
    {
        if (char.IsDigit(strNewPassword[i]))
            digits++;
    
        if (char.IsSymbol(strNewPassword[i]) || char.IsPunctuation(strNewPassword[i]))
            symbols++;
    
        if (char.IsLower(strNewPassword[i]))
            lowercase++;
    
        if (char.IsUpper(strNewPassword[i]))
            uppercase++;
    }
    
    WriteLine("=====================================");
    WriteLine("Password Analysis");
    WriteLine("-------------------------------------");
    WriteLine("Digits:            {0}", digits);
    WriteLine("Symbols:           {0}", symbols);
    WriteLine("Lowercase Letters: {0}", lowercase);
    WriteLine("Uppercase Letters: {0}", uppercase);
    WriteLine("-------------------------------------");
    WriteLine("Characters:        {0}", length);
    WriteLine("=====================================");
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. When requested, for the New Password, simply press Enter:
    New Password:
    You cannot have a null or white space password (a password with no character at all). You must create a new password that conforms to this company's password rules.
    
    Press any key to close this window . . .
  4. Close the window and return to your programming environment
  5. To execute the project again, on the main menu, click Debug -> Start Without Debugging
  6. When requested, for the New Password, type P@s$w0rd#1009 and press Enter:
    New Password: P@s$w0rd#1009
    =====================================
    Password Analysis
    -------------------------------------
    Digits:            5
    Symbols:           3
    Lowercase Letters: 4
    Uppercase Letters: 1
    -------------------------------------
    Characters:        13
    =====================================
    
    Press any key to close this window . . .
  7. Close the window and return to your programming environment

Strings and Classes

Strings and Classes/Records/Structures

As we saw in previous lessons, you can create a field or a property of a string type. You can create a method that returns a string and you can pass a string a parameter to a method.

A String-Based Property

You already know that when you are creating a class, if you add a string-based property, the compiler will present a warning to let you know that the property may eventually hold null values. There are various ways you can work with this issue. If you are creating a complete property, you can initialize its associated field in a constructor. This can be done as follows:

using static System.Console;

House prop = new()
{
    Bedrooms = 5, Bathrooms = 3.50f, PropertyNumber = 850_248, MarketValue = 575_800d
};

WriteLine("Altair Realtors");
WriteLine("==========================");
WriteLine("Property Inventory");
WriteLine("--------------------------");
WriteLine("Property #:   {0}", prop.PropertyNumber);
WriteLine("Bedrooms:     {0}", prop.Bedrooms);
WriteLine("Bathrooms:    {0}", prop.Bathrooms);
WriteLine("Condition:    {0}", prop.Condition);
WriteLine("Market Value: {0:C}", prop.MarketValue);
WriteLine("==========================");

public class House
{
    string cond;

    public House()
    {
        cond = "Excellent";
    }

    public int    PropertyNumber { get; set; }
    public int    Bedrooms       { get; set; }
    public float  Bathrooms      { get; set; }

    public string Condition
    {
        set
        {
            cond = value;
        }

        get
        {
            return cond;
        }
    }

    public double MarketValue { get; set; }
}

This would produce:

Altair Realtors
==========================
Property Inventory
--------------------------
Property #:   850248
Bedrooms:     5
Bathrooms:    3.5
Condition:    Excellent
Market Value: $575,800.00
==========================

Press any key to close this window . . .

If you are creating an automatic property, you can assign a constant value to it. This can be done as follows:

public class House
{
    public int    PropertyNumber { get; set; }
    public int    Bedrooms { get; set; }
    public float  Bathrooms { get; set; }
    public string Condition { get; set; } = "Available";
    public double MarketValue { get; set; }
}

If you don't have or don't know a value to use, you can initialize the property with string.Empty, This can be done as follows:

public class House
{
    public int    PropertyNumber { get; set; }
    public int    Bedrooms { get; set; }
    public float  Bathrooms { get; set; }
    public string Condition { get; set; } = "Available";
    public string SaleStatus { get; set; } = string.Empty;
    public double MarketValue { get; set; }
}

As we saw in previous lessons, another and probably better solution is to apply the null-conditional operator to the String type of the property. This can be done as follows:

public class House
{
    public int     PropertyNumber { get; set; }
    public int     Bedrooms       { get; set; }
    public float   Bathrooms      { get; set; }
    public string? Condition      { get; set; }
    public string? SaleStatus     { get; set; }
    public double  MarketValue    { get; set; }
}

Strings Comparisons

String Equality

The indexed-equivalent characters of two strings can be compared to know whether one is lower or higher than the other. If you are only interested to know whether two strings are equivalent, to assist you with that operation, the string type is equipped with a method named Equals. It is overloaded with various versions. Two versions use the following syntaxes:

public override bool Equals(object obj);
public bool Equals(string value);

When calling one of these versions, use an object object or a string value that calls it. The method takes one argument. The variable that calls the method is compared to the value passed as argument. If both values are the exact same, the method returns true. The comparison is performed considering the case of each character. If you don't want to consider the case, use the following version of the method:

public bool Equals(string value, StringComparison comparisonType);

An alternative to the second syntax is to use a static version of this method whose syntax is:

public static bool Equals(string a, string b);

This method takes two string arguments and compares them. If they are the same, the method returns true. This method considers the cases of the characters. If you don't want this factor taken into consideration, use the following version of the method:

public static bool Equals(string a,
			  string b,
			  StringComparison comparisonType);

String Integral Comparison

String comparison consists of examining the characters of two strings with a character of one string compared to a character of the other string with both characters at the same positions. To support this operation, the String class (and therefore the string data type) is equipped with a method named Compare(), That method is overloaded with many versions. One of the versions uses the following syntax:

public static int Compare(string String1, string  String2);

This method is declared static and it takes two arguments. The method returns

Here are three examples of calling this method:

using static System.Console;

string firstName1 = "Andy";
string lastName1 = "Stanley";
string firstName2 = "Charles";
string lastName2 = "Stanley";

int Value1 = string.Compare(firstName1, firstName2);
int Value2 = string.Compare(firstName2, firstName1);
int Value3 = string.Compare(lastName1, lastName2);

WriteLine("=============================================");
WriteLine("\"{0}\"    compared to \"{1}\" produces {2}", firstName1, firstName2, Value1);
WriteLine("\"{0}\" compared to \"{1}\"    produces  {2}", firstName2, firstName1, Value2);
WriteLine("\"{0}\" compared to \"{1}\" produces  {2}", lastName1, lastName2, Value3);
WriteLine("=============================================");

This would produce:

=============================================
"Andy"    compared to "Charles" produces -1
"Charles" compared to "Andy"    produces  1
"Stanley" compared to "Stanley" produces  0
=============================================
Press any key to close this window . . .

When using this version of the string.Compare() method, the case (upper or lower) of each character is considered. If you don't want to consider this factor, the String class proposes another version of the method. Its syntax is:

public static int Compare(string String1, string String2, bool ignoreCase);

The third argument allows you to ignore the case of the characters when performing the comparison.

Practical LearningPractical Learning: Integrally Comparing Strings

  1. Change the document as follows:
    using static System.Console;
    
    bool passwordsMatched = false;
    string strNewPassword = string.Empty;
    string strConfirmPassword = string.Empty;
    int digits = 0, symbols = 0, lowercase = 0, uppercase = 0;
    
    Write("New Password:     ");
    strNewPassword = ReadLine()!;
    
    if (string.IsNullOrWhiteSpace(strNewPassword))
    {
        WriteLine("You cannot have a null or white space password (a password with no character at all). " +
                  "You must create a new password that conforms to this company's password rules.");
    }
    
    Write("Confirm Password: ");
    strConfirmPassword = ReadLine()!;
    
    if (string.IsNullOrWhiteSpace(strConfirmPassword))
    {
        WriteLine("You must type the same password a second time.");
    }
    
    if (string.Compare(strNewPassword, strConfirmPassword) == 0)
    {
        WriteLine("-----------------------------------------");
        WriteLine("Your password will be saved successfully.");
        passwordsMatched = true;
    }
    else
    {
        WriteLine("-------------------------------------");
        WriteLine("The passwords don't match.");
    }
    
    if (passwordsMatched == true)
    {
        int length = strNewPassword.Length;
    
        for (int i = 0; i < length; i++)
        {
            if(char.IsDigit(strNewPassword[i]))
                digits++;
    
            if(char.IsSymbol(strNewPassword[i]) || char.IsPunctuation(strNewPassword[i]))
                symbols++;
    
            if(char.IsLower(strNewPassword[i]))
                lowercase++;
    
            if(char.IsUpper(strNewPassword[i]))
                uppercase++;
        }
    
        WriteLine("=========================================");
        WriteLine("Password Analysis");
        WriteLine("-----------------------------------------");
        WriteLine("Digits:            {0}", digits);
        WriteLine("Symbols:           {0}", symbols);
        WriteLine("Lowercase Letters: {0}", lowercase);
        WriteLine("Uppercase Letters: {0}", uppercase);
        WriteLine("-----------------------------------------");
        WriteLine("Characters:        {0}", length);
    }
            
    WriteLine("=========================================");
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the New Password as $outhD@KoTA1889 and press Enter
  4. For the Confirm Password, type $0uthD@koTA1889 and press Enter:
    New Password:     $outhD@KoTA1889
    Confirm Password: $0uthD@koTA1889
    -------------------------------------
    The passwords don't match.
    =========================================
    
    Press any key to close this window . . .
  5. Close the window and return to your programming environment
  6. To execute the application, on the main menu, click Debug -> Start Without Debugging
  7. When requested, type the New Password as $outhD@KoTA1889 and press Enter
  8. For the Confirm Password, type $outhD@KoTA1889 and press Enter:
    New Password:     $outhD@KoTA1889
    Confirm Password: $outhD@KoTA1889
    -----------------------------------------
    Your password will be saved successfully.
    =========================================
    Password Analysis
    -----------------------------------------
    Digits:            4
    Symbols:           2
    Lowercase Letters: 5
    Uppercase Letters: 4
    -----------------------------------------
    Characters:        15
    =========================================
    
    Press any key to close this window . . .
  9. Close the window and return to your programming environment
  10. Create a new Console App (that supports .NET 8.0 (Long-Term Support)) named Chemistry3
  11. In the Solution Explorer, right-click Chemistry3 -> Add -> Class...
  12. Type the name of the file as Element
  13. Click Add
  14. Populate the document as follows:
    namespace Chemistry3
    {
        public enum Phase { Gas, Liquid, Solid, Unknown }
    
        public record Element
        {
            internal string? Symbol       { get; init; }
            internal string? ElementName  { get; init; }
            internal int     AtomicNumber { get; init; }
            internal double  AtomicWeight { get; init; }
            internal Phase   Phase        { get; init; }
    
            public Element() { }
            public Element(int number)    => AtomicNumber = number;
            public Element(string symbol) => Symbol = symbol;
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                Symbol       = symbol;
                AtomicNumber = number;
            }
        }
    }
  15. In the Solution Explorer, right-click Program.cs and click Rename
  16. Type Chemistry (to get Chemistry.cs) and press Enter twice

String-Case Conversions

Converting a String to Lowercase

To let you convert a string from lowercase to uppercase, the String class is equipped with a method named ToLower. It is overloaded with two versions. One of the versions of this method uses the following syntax:

public string ToLower();

This method considers each character of the string that called it. If the character is already in uppercase, it would not change. If the character is a lowercase alphabetic character, it would be converted to uppercase. If the character is not an alphabetic character, it would be kept "as-is".

Practical LearningPractical Learning: Converting a String to Lowercase

  1. Change the document as follows:
    using static System.Console;
    using Chemistry3;
    
    WriteLine("===========================");
    Write("Type a chemical symbol: ");
    string strSelected = ReadLine()!;
    
    string converted = strSelected.ToLower();
    WriteLine("===========================");
    
    Clear();
    
    Element elm = IdentifyElement(converted);
    
    Present(elm);
                
    Element IdentifyElement(string identifier)
    {
        Element H = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas);
        Element He = new Element(2, "He", "Helium", 4.002602, Phase.Gas);
        Element Li = new Element(3, "Li", "Lithium", 6.94, Phase.Solid);
        Element Be = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
        Element B = new Element(5, "B", "Boron", 10.81, Phase.Solid);
        Element C = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6, phase: Phase.Solid);
        Element N = new Element(7) { Symbol = "N", AtomicWeight = 14.007, ElementName = "Nitrogen", Phase = Phase.Gas };
        Element O = new Element("O") { AtomicNumber = 8, ElementName = "Oxygen", AtomicWeight = 15.999, Phase = Phase.Gas };
        Element F = new Element("F") { AtomicNumber = 9, ElementName = "Fluorine", AtomicWeight = 15.999, Phase = Phase.Gas };
        Element Ne = new Element("Ne") { AtomicNumber = 10, ElementName = "Neon", AtomicWeight = 20.1797, Phase = Phase.Gas };
        Element Na = new Element(11, "Na", "Sodium", 22.98976928, Phase.Solid);
    
        Element selected = new Element();
    
        switch (identifier)
        {
            default:
                selected = new Element(0, "", "Known", 0.00, Phase.Unknown); ;
                break;
            case "na":
                selected = Na;
                break;
            case "o":
                selected = O;
                break;
            case "he":
                selected = He;
                break;
            case "c":
                selected = C;
                break;
            case "be":
                selected = Be;
                break;
            case "h":
                selected = H;
                break;
            case "li":
                selected = Li;
                break;
            case "b":
                selected = B;
                break;
            case "ne":
                selected = Ne;
                break;
            case "f":
                selected = F;
                break;
            case null:
                selected = new Element(0, "", "Known", 0.00, Phase.Unknown); ;
                break;
            case "n":
                selected = N;
                break;
        }
    
        return selected;
    }
    
    void Present(Element obj)    
    {
        if (obj is null)
            throw new System.Exception("Bad Argument");
    
        WriteLine("Chemistry");
        WriteLine("--------------------------");
        WriteLine("Symbol:        " + obj.Symbol);
        WriteLine($"Atomic Number: {obj.AtomicNumber}");
        WriteLine("Element Name:  " + obj.ElementName);
        WriteLine($"Atomic Weight: " + obj.AtomicWeight);
        WriteLine($"Phase:         " + obj.Phase);
        WriteLine("==========================");
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the Chemical Symbol as NA
    ===========================
    Type a chemical symbol: NA
  4. Press Enter
    Chemistry
    --------------------------
    Symbol:        Na
    Atomic Number: 11
    Element Name:  Sodium
    Atomic Weight: 22.98976928
    Phase:         Solid
    ==========================
    
    Press any key to close this window . . .
  5. Close the window and return to your programming environment
  6. Start a new Console App (that supports .NET 8.0 (Long-Term Support)) named TaxPreparation8
  7. In the Solution Explorer, right-click PayrollEvaluation06 -> Add -> Class...
  8. Type the Name of the file as IncomeTax
  9. Press Enter
  10. Change the class as follows:
    namespace TaxPreparation8
    {
        public class State
        {
            private string? abrv;
    
            public State(string abbrv)
            {
                abrv = abbrv;
            }
    
            public string? Abbreviation
            {
                get  { return abrv; }
                init { abrv = value; }
            }
        }
    }

Converting a String to Uppercase

To let you convert a string to uppercase, the String class is equipped with a method named ToUpper. This method is overloaded with two versions. The syntax of one of the versions is:

public string ToUpper()

Here is an example:

using static System.Console;

string strFullName = "Alexander Patrick Katts";
string strUppercase = strFullName.ToUpper();

WriteLine("======================================");
WriteLine("Full Name:    {0}", strFullName);
WriteLine("In Uppercase: {0}", strUppercase);
WriteLine("======================================");

This would produce:

======================================
Full Name:    Alexander Patrick Katts
In Uppercase: ALEXANDER PATRICK KATTS
======================================
Press any key to close this window . . .

Practical LearningPractical Learning: Converting a String to Uppercase

  1. Change the IncomeTax.cs document as follows:
    namespace TaxPreparation8
    {
        public class State
        {
            private string? abrv;
            private string? _nm_;
    
            public State(string? abbrv)
            {
                abrv = abbrv?.ToUpper();
            }
    
            public string? Abbreviation
            {
                get  { return abrv; }
                init { abrv = value; }
            }
    
            public string? Name
            {
                get
                {
                    switch (abrv)
                    {
                        case "CO":
                            _nm_ = "Colorado";
                            break;
                        case "FL":
                            _nm_ = "Florida";
                            break;
                        case "KY":
                            _nm_ = "Kentucky";
                            break;
                        case "IL":
                            _nm_ = "Illinois";
                            break;
                        case "IN":
                            _nm_ = "Indiana";
                            break;
                        case "MA":
                            _nm_ = "Massachusetts";
                            break;
                        case "MI":
                            _nm_ = "Michigan";
                            break;
                        case "NC":
                            _nm_ = "North Carolina";
                            break;
                        case "NH":
                            _nm_ = "New Hampshire";
                            break;
                        case "NV":
                            _nm_ = "Nevada";
                            break;
                        case "PA":
                            _nm_ = "Pennsylvania";
                            break;
                        case "TN":
                            _nm_ = "Tennessee";
                            break;
                        case "TX":
                            _nm_ = "Texas";
                            break;
                        case "UT":
                            _nm_ = "Utah";
                            break;
                        case "WA":
                            _nm_ = "Washington";
                            break;
                        case "WY":
                            _nm_ = "Wyoming";
                            break;
                        case "MO":
                            _nm_ = "Missouri";
                            break;
                        case "MT":
                            _nm_ = "Montana";
                            break;
                    }
    
                    return _nm_;
                }
            }
    
        }
    
        public class IncomeTax
        {
            private double grsSal;
    
            public State State { get; set; } = new State("OO");
    
            public double GrossSalary
            {
                set { grsSal = value; }
                get { return grsSal; }
            }
    
            public double TaxAmount
            {
                get
                {
                    double amt = 0.00;
    
                    switch (State.Abbreviation)
                    {
                        case "CO":
                            amt = GrossSalary * 4.63 / 100;
                            break;
                        case "FL":
                        case "NV":
                        case "TX":
                        case "WA":
                        case "WY":
                            amt = 0.00;
                            break;
                        case "KY":
                        case "MA":
                        case "NH":
                            amt = GrossSalary * 5.00 / 100;
                            break;
                        case "IL":
                        case "UT":
                            amt = GrossSalary * 4.95 / 100;
                            break;
                        case "IN":
                            amt = GrossSalary * 3.23 / 100;
                            break;
                        case "MI":
                            amt = GrossSalary * 4.25 / 100;
                            break;
                        case "NC":
                            amt = GrossSalary * 5.25 / 100;
                            break;
                        case "PA":
                            amt = GrossSalary * 3.07 / 100;
                            break;
                        case "TN":
                            amt = GrossSalary * 1.00 / 100;
                            break;
                        case "MO":
                            // Missouri
                            if ((GrossSalary >= 0.00) && (GrossSalary <= 106))
                            {
                                amt = 0.00;
                            }
                            else if ((GrossSalary > 106) && (GrossSalary <= 1_073))
                            {
                                amt = GrossSalary * 1.50 / 100;
                            }
                            else if ((GrossSalary > 1_073) && (GrossSalary <= 2_146))
                            {
                                amt = 16 + (GrossSalary * 2.00 / 100);
                            }
                            else if ((GrossSalary > 2_146) && (GrossSalary <= 3_219))
                            {
                                amt = 37 + (GrossSalary * 2.50 / 100);
                            }
                            else if ((GrossSalary > 3_219) && (GrossSalary <= 4_292))
                            {
                                amt = 64 + (GrossSalary * 3.00 / 100);
                            }
                            else if ((GrossSalary > 4_292) && (GrossSalary <= 5_365))
                            {
                                amt = 96 + (GrossSalary * 3.50 / 100);
                            }
                            else if ((GrossSalary > 5_365) && (GrossSalary <= 6_438))
                            {
                                amt = 134 + (GrossSalary * 4.00 / 100);
                            }
                            else if ((GrossSalary > 6_438) && (GrossSalary <= 7_511))
                            {
                                amt = 177 + (GrossSalary * 4.50 / 100);
                            }
                            else if ((GrossSalary > 7_511) && (GrossSalary <= 8_584))
                            {
                                amt = 225 + (GrossSalary * 5.00 / 100);
                            }
                            else // if(GrossSalary > 8_584)
                            {
                                amt = 279 + (GrossSalary * 5.40 / 100);
                            }
                            break;
    
                        case "MT":
                            /* Montana
                             * https://montana.servicenowservices.com/citizen/kb?id=kb_article_view&sysparm_article=KB0014487
                             * 2020 Individual Income Tax Rates
                             * If your taxable income is more than	but not more than	Your tax is	minus
                             * $0	    $3,100	1% of your taxable income	$0
                             * $3,100	$5,500	2% of your taxable income	$31
                             * $5,500	$8,400	3% of your taxable income	$86
                             * $8,400	$11,300	4% of your taxable income	$170
                             * $11,300	$14,500	5% of your taxable income	$283
                             * $14,500	$18,700	6% of your taxable income	$428
                             * $18,700	6.9% of your taxable income	$596 */
                            if ((GrossSalary >= 0.00) && (GrossSalary <= 3_100))
                            {
                                amt = (GrossSalary * 1 / 100);
                            }
                            else if ((GrossSalary > 3_100) && (GrossSalary <= 5_500))
                            {
                                amt = (GrossSalary * 2 / 100) - 31;
                            }
                            else if ((GrossSalary > 5_500) && (GrossSalary <= 8_400))
                            {
                                amt = (GrossSalary * 3 / 100) - 86;
                            }
                            else if ((GrossSalary > 8_400) && (GrossSalary <= 11_300))
                            {
                                amt = (GrossSalary * 4 / 100) - 170;
                            }
                            else if ((GrossSalary > 11_300) && (GrossSalary <= 14_500))
                            {
                                amt = (GrossSalary * 5 / 100) - 283;
                            }
                            else if ((GrossSalary > 14_500) && (GrossSalary <= 18_700))
                            {
                                amt = (GrossSalary * 6 / 100) - 428;
                            }
                            else // if(grossSalary > 18_700)
                            {
                                amt = (GrossSalary * 6.90 / 100) - 596;
                            }
                            break;
                    }
    
                    return amt;
                }
            }
    
            public double NetPay
            {
                get { return grsSal - TaxAmount; }
            }
        }
    }
  2. In the Solution Explorer, rename Program.cs as TaxPreparation.cs and access it
  3. Change the TaxPreparation.cs document as follows:
    using static System.Console;
    using TaxPreparation8;
    
    IncomeTax tax = GetState();
    
    Write("Gross Salary:             ");
    tax.GrossSalary = double.Parse(ReadLine()!);
    
    WriteLine("============================================");
    WriteLine(" - Amazing DeltaX - State Income Tax -");
    WriteLine("--------------------------------------------");
    WriteLine($"           {tax.State.Name}");
    WriteLine($"Gross Salary: {tax.GrossSalary:f}");
    WriteLine("--------------------------------------------");
    WriteLine($"Tax Amount:   {tax.TaxAmount:f}");
    WriteLine($"Net Pay:      {tax.NetPay:f}");
    WriteLine("============================================");
                
    IncomeTax GetState()
    {
        IncomeTax t = new IncomeTax();
    
        WriteLine("==========================================");
        WriteLine(" - Amazing DeltaX - State Income Tax -");
        WriteLine("==========================================");
    
        WriteLine("Enter the information for tax preparation");
        WriteLine("States");
        WriteLine(" AK - Alaska");
        WriteLine(" AR - Arkansas");
        WriteLine(" CO - Colorado");
        WriteLine(" FL - Florida");
        WriteLine(" GA - Georgia");
        WriteLine(" IL - Illinois");
        WriteLine(" IN - Indiana");
        WriteLine(" KY - Kentucky");
        WriteLine(" MA - Massachusetts");
        WriteLine(" MI - Michigan");
        WriteLine(" MO - Missouri");
        WriteLine(" MS - Mississippi");
        WriteLine(" NV - Nevada");
        WriteLine(" NH - New Hampshire");
        WriteLine(" NC - North Carolina");
        WriteLine(" PA - Pennsylvania");
        WriteLine(" SD - South Dakota");
        WriteLine(" TN - Tennessee");
        WriteLine(" TX - Texas");
        WriteLine(" UT - Utah");
        WriteLine(" WA - Washington");
        WriteLine(" WY - Wyoming");
        Write("Enter State Abbreviation: ");
        string selection = ReadLine()!;
        WriteLine("--------------------------------------------");
    
        t.State = new State(selection);
    
        return t;
    }
  4. To execute the project, on the main menu, click Debug -> Start Without Debugging
  5. When requested, for the State Abbreviation, type nv and press Enter
  6. For the Gross Salary, type 6248.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: nv
    --------------------------------------------
    Gross Salary:             6248.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
               Nevada
    Gross Salary: 6248.85
    --------------------------------------------
    Tax Amount:   0.00
    Net Pay:      6248.85
    ============================================
    
    Press any key to close this window . . .
  7. Press Y to close the window and return to your programming environment
  8. To execute the project again, on the main menu, click Debug -> Start Without Debugging
  9. When requested, for the State Abbreviation, type Ut and press Enter
  10. For the Gross Salary, type 6248.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: Ut
    --------------------------------------------
    Gross Salary:             6248.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
               Utah
    Gross Salary: 6248.85
    --------------------------------------------
    Tax Amount:   309.32
    Net Pay:      5939.53
    ============================================
    
    Press any key to close this window . . .
  11. Press H to close the window and return to your programming environment
  12. To execute again, on the main menu, click Debug -> Start Without Debugging
  13. When requested, for the State Abbreviation, type mO and press Enter
  14. For the Gross Salary, type 6248.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: mO
    --------------------------------------------
    Gross Salary:             6248.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
               Missouri
    Gross Salary: 6248.85
    --------------------------------------------
    Tax Amount:   383.95
    Net Pay:      5864.90
    ============================================
    
    Press any key to close this window . . .
  15. Press N to close the window and return to your programming environment
  16. To execute again, on the main menu, click Debug -> Start Without Debugging
  17. When requested, for the State Abbreviation, type mt and press Enter
  18. For the Gross Salary, type 6248.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: mt
    --------------------------------------------
    Gross Salary:             6248.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
               Montana
    Gross Salary: 6248.85
    --------------------------------------------
    Tax Amount:   101.47
    Net Pay:      6147.38
    ============================================
    
    Press any key to close this window . . .
  19. Press U to close the window and return to your programming environment
  20. Close your programming environment

Previous Copyright © 2001-2024, FunctionX Friday 15 October 2021 Next