This is OrderStatus enum:
public enum OrderStatus
{
[Display(Name = "Gözləmədə")]
Pending,
[Display(Name = "Qəbul olundu")]
Accepted,
[Display(Name = "Ləğv edildi")]
Rejected,
[Display(Name = "Çatdırıldı")]
Delivered
}
This is Order model:
public class Order : BaseEntity
{
public string AppUserId { get; set; }
public AppUser AppUser { get; set; }
[StringLength(255), Required]
public string StoreName { get; set; }
[StringLength(255), Required]
public string StoreAddress { get; set; }
public double TotalPrice { get; set; }
public double RemainingBalance { get; set; }
public ShippingMethod ShippingMethod { get; set; }
public OrderStatus Status { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public IEnumerable<OrderItem> OrderItems { get; set; }
public IEnumerable<Payment> Payments { get; set; }
}
And there is a switch statement in the OrderController to filter data:
private async Task<IEnumerable<Order>> PaginateAsync(string status, int page)
{
ViewBag.Status = status;
ViewBag.CurrentPage = page;
int perPage = 10;
ViewBag.PerPage = perPage;
IEnumerable<Order> orders = await _context.Orders
.Include(o => o.AppUser)
.Include(o => o.OrderItems)
.Where(o => !o.IsDeleted)
.OrderByDescending(o => o.Id)
.ToListAsync();
orders = status switch
{
"pending" => orders.Where(o => (int)o.Status == 0),
"accepted" => orders.Where(o => (int)o.Status == 1),
"rejected" => orders.Where(o => (int)o.Status == 2),
"delivered" => orders.Where(o => (int)o.Status == 3),
_ => orders
};
ViewBag.PageCount = Math.Ceiling((double)orders.Count() / perPage);
return orders.Skip((page - 1) * perPage).Take(perPage);
}
My question is: Why is cast to integer redundant? I need to cast the values to int to compare them in accepted, rejected, and delivered cases, but not pending case. Why is it unnecessary in pending case?

Actually, this is just question, not a problem.
Why is cast to integer redundant
As you have noticed that not all casts are redundant but only a specific one - from 0.
Found in the specification "Implicit enumeration conversions" section:
An implicit enumeration conversion permits a
constant_expression(§11.23) with any integer type and the value zero to be converted to anyenum_typeand to anynullable_value_typewhose underlying type is anenum_type. In the latter case the conversion is evaluated by converting to the underlyingenum_typeand wrapping the result.
So there implicit conversion from 0 constant to your enum exists, so no explicit cast is required. Hence:
const byte bZero = 0;
MyEnum me = bZero; // Compiles
MyEnum me1 = 0; // Compiles
// MyEnum me2 = 1; // Does not compile
enum MyEnum
{
None = 10,
One,
Two
}
Demo@sharplab
P.S.
Thanks to @Rand Random for the pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With