Use of unassigned variable?

2019-03-01 05:27发布

问题:

I'm getting the error use of unassigned variable "ps" when declaring if paymentstatus is null or has value in the "if" statement. I'm thinking that i allready declared ps but obviously im doing something wrong. Why does the compiler complain about this?

Here's the error in it's context:

public IList<BestsellersReportLine> DailyBestsellersReport()
        {


            OrderStatus os; 
            PaymentStatus? ps; 
            ShippingStatus ss;
            int billingCountryId = 0;
            int recordsToReturn = 999; 
            int orderBy = 1;
            int groupBy = 1;



            int? paymentStatusId = null;
            if (ps.HasValue)
                paymentStatusId = (int)ps.Value;



            // Specifies the time range for sold products/day
            var range = new
            {
                startTimeUtc = DateTime.Today.AddDays(-1),
                endTimeUtc = DateTime.Today.AddSeconds(-1),



                CreatedOnUtc = DateTime.Today.AddDays(-1),

            };




            var query1 = from opv in _opvRepository.Table
                         join o in _orderRepository.Table on opv.OrderId equals o.Id
                         join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
                         join p in _productRepository.Table on pv.ProductId equals p.Id
                         where (o.CreatedOnUtc >= range.startTimeUtc && o.CreatedOnUtc <= range.endTimeUtc) &&
                         (!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId)
                         select opv;
}

Thank you!

回答1:

You have declared the local variable but you have not assigned a value. Therefore the compiler helps you to prevent this bug.

PaymentStatus? ps;  
// ...
if (ps.HasValue)

So assign a value:

PaymentStatus? ps = null;  
// ...
if (ps.HasValue)

However, thix fixes the compiler error but is still pointless since it will never have a value. Maybe you want to use a method parameter instead:

public IList<BestsellersReportLine> DailyBestsellersReport(PaymentStatus? ps)
{


回答2:

Initialize your ps variable like

PaymentStatus? ps = null; //or something. 

From Compiler Error CS0165

C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165



回答3:

It is an unassigned variable i.e. you havent initialised it with a value.



回答4:

Yes, you did declare the variable.

Yet it says "unassigned" not "undeclared", and you didn't assign any value to the variable. Just set it to null.



回答5:

You haven't initialized ps...you need to initalize it with at least null value...

PaymentStatus? ps = null;

The same applies to all other variables