简体   繁体   中英

Getting error “Use of unassigned local variable” in C#

I'm quite new to programming so forgive me if this is a simple fix. I am consistently getting an error "Use of unassigned local variable" in regards to to my string variable "city". What's confusing me is that I also have a string variable called "centreName" which does not bring up the same error even though it is also not initialized.

The point of this program is to have users input data for the name of a Science Centre and the city it's located in. I have tried initializing the "city" variable to both string city = null and string city = "" , but when I run the program, the output shows up blank as opposed to what the user entered. This is not the case with my "centreName" var.

I will include the coding for both classes I am using. Please disregard my methods as I have yet to tweak them to fit this program. They are older methods I used for something previous and the coding does not apply here.

This is the class in which I'm getting the error:

class ScienceCentreApp
{
    static void Main(string[] args)
    {
        string centreName;
        string city;
        decimal ticketPrice = 0;
        int visitorCnt;
        string[] dArray = new String[5];
        int[] adultVisitors = new int[5];
        decimal[] totalRevenue = new decimal[5];
        char enterMoreData = 'Y';
        ScienceCentreVisitation scv;


        do
        {
            visitorCnt = GetData(out centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
            scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
            Console.Clear();
            Console.WriteLine(scv);

            Console.Write("\n\n\n\nDo you want to enter more data - " +
                          "(Enter y or n)? ");
            if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
                Console.WriteLine("Invalid data entered - " +
                                    "No recorded for your respones");
        } while (enterMoreData == 'y' || enterMoreData == 'y');

        Console.ReadKey();
    }

    public static int GetData(out string centreName, string city, decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
    {
        int i,
            loopCnt;

        Console.Clear();
        Console.Write("Name of Centre: ");
        centreName = Console.ReadLine();
        Console.Write("City: ");
        city = Console.ReadLine();
        Console.Write("Ticket Price: ");
        string inValue = Console.ReadLine();
        ticketPrice = Convert.ToDecimal(inValue);
        Console.Write("How many records for {0}? ", centreName);
        string inValue1 = Console.ReadLine();
        if (int.TryParse(inValue1, out loopCnt) == false)
            Console.WriteLine("Invalid data entered - " +
                                "0 recorded for number of records");
        for (i = 0; i < loopCnt; i++)
        {
            Console.Write("\nDate (mm/dd/yyyy): ");
            dArray[i] = Console.ReadLine();
            if (dArray[i] == "")
            {
                Console.WriteLine("No date entered - " +
                                    "Unknown recorded for visits");
                dArray[i] = "Unknown";
            }
            Console.Write("Number of One-Day Adult Visitors: ");
            inValue1 = Console.ReadLine();
            if (int.TryParse(inValue1, out adultVisitors[i]) == false)
                Console.WriteLine("Invalid data entered - " +
                                    "0 recorded for adults visited");
        }
        return i;
    }
}

}

This is the other class that the first is calling:

class ScienceCentreVisitation
{
    private string centreName;
    private string city;
    private decimal ticketPrice;
    private string[] visitDate;
    private int[] adultVisitors;
    private decimal[] totalRevenue;


    //constructors
    public ScienceCentreVisitation()
    {

    }

    public ScienceCentreVisitation(string cent)
    {
        centreName = cent;
    }

    public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
    {
        visitDate = new string[date.Length];
        adultVisitors = new int[visit.Length];
        totalRevenue = new decimal[rev.Length];
        Array.Copy(date, 0, visitDate, 0, date.Length);
        Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
        Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
        centreName = cent;
        city = cit;
        ticketPrice = price;
    }

    //properties
    public string CentreName
    {
        get
        {
            return centreName;
        }
        set
        {
            centreName = value;
        }
    }

    public string City
    {
        get
        {
            return city;
        }
        set
        {
            city = value;
        }
    }

    public decimal TicketPrice
    {
        get
        {
            return ticketPrice;
        }
        set
        {
            ticketPrice = value;
        }
    }

    public string[] VisitDate
    {
        get
        {
            return visitDate;
        }
        set
        {
            visitDate = value;
        }
    }

    public int[] AdultVisitors
    {
        get
        {
            return adultVisitors;
        }
        set
        {
            adultVisitors = value;
        }
    }

    public decimal[] TotalRevenue
    {
        get
        {
            return totalRevenue;
        }
        set
        {
            totalRevenue = value;
        }
    }

    //methods
    public decimal CalculateTotalRevenue()
    {
        decimal totalRev;

        int cntOfValidEntries;
        int total = 0;
        foreach (int c in adultVisitors)
            total += c;
        cntOfValidEntries = TestForZeros();
        totalRev = (decimal)total / cntOfValidEntries;
        return totalRev;
    }

    public int TestForZeros()
    {
        int numberOfTrueVisits = 0;
        foreach (int cnt in adultVisitors)
            if (cnt != 0)
                numberOfTrueVisits++;
        return numberOfTrueVisits;
    }

    public int GetIndexOfLeastVisited()
    {
        int minVisIndex = 0;

        for (int i = 1; i < adultVisitors.Length; i++)
            if (adultVisitors[i] > adultVisitors[minVisIndex])
                minVisIndex = i;
        return minVisIndex;
    }

    public int GetLeastVisited()
    {
        return adultVisitors[GetIndexOfLeastVisited()];
    }

    public string GetDateWithLeastVisited()
    {
        return visitDate[GetIndexOfLeastVisited()];
    }

    public int GetIndexOfMostRevenue()
    {
        int maxRevIndex = 0;

        for (int i = 1; i < totalRevenue.Length; i++)
            if (totalRevenue[i] > totalRevenue[maxRevIndex])
                maxRevIndex = i;
        return maxRevIndex;
    }

    public decimal GetMostRevenue()
    {
        return totalRevenue[GetIndexOfMostRevenue()];
    }

    public string GetDateWithMostRevenue()
    {
        return visitDate[GetIndexOfMostRevenue()];
    }

    public override string ToString()
    {
        return "Name of Centre: " + centreName +
               "\nCity: " + city +
                "\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
                "\nNumber of Least One-Day Adult Visitors: \t\t" + GetLeastVisited() +
                "\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
                "\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
    }
}

}

Thanks in advance!

The difference between centreName and city is that centreName is used as an out parameter. That means you can call the method with an uninitialized variable because it is guaranteed that the variable will be assigned a value inside the method.

In your case, both centreName and city are assigned values in GetData , so you can safely replace string city with out string city .

centreName is declared as an out parameter (meaning it will retain the last value you assign to it inside the method when you leave the method's scope), so it is getting initialized by get data. The rest of your variables are not being set by the get data call, because they are not out parameters.

On that point, out parameters are generally considered bad practice in C# (I can't speak to other languages). Most they obscure the purpose of the method, and it is very easy to accidentally overwrite the value of one of the out parameters after the method is called (or mistakenly initialize it). Instead of using out parameters, create an object that wraps your data and return that instead of an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM