How to assign a default date on a Datetime type object in C#?

Asked

Viewed 395 times

2

I created a class called Order, and in it I created a field for the purpose of entering a date of delivery of the order.

But I created the object on Main(), and at the time I execute it fills in with the date default, I’ve already done the debug but I don’t know where I’m going wrong.

This is my class Order:

namespace SergioS_301011342_LIB
{
    public class Order
    {
        private DateTime orderDateMade;
        private DateTime orderDateDeli;
        private AddressStruct orderAddressDeli;
        private decimal cost;
        private Customer customer;
        private static int orderNumber;
        private OrderItem[] orderItems;
        private int noOrders;
        private const uint MAX_NUMBER_OF_ORDERS = 50;

        public Order()
        {
            orderItems = new OrderItem[MAX_NUMBER_OF_ORDERS];
            noOrders = 0;
            orderNumber += 1;
            orderDateDeli = new DateTime();
        }

        public Customer Customer
        {
            get { return customer; }
            set { customer = value; }
        }

        public OrderItem[] OrderItems
        {
            get { return orderItems; }
            set { orderItems = value; }
        }

        public int OrderId
        {
            get { return orderNumber; }
        }

        public DateTime OrderDateMade
        {
            get { return orderDateMade; }
            set { orderDateMade = DateTime.Now; }

        }
        public DateTime OrderDateDeli
         {
          get { return orderDateDeli; }
            set { orderDateMade = DateTime.Today; }

        }
        public AddressStruct OrderAddressDeli
        {
            get { return orderAddressDeli; }
            set {orderAddressDeli = value; }
        }
        public decimal Cost
        {
            get { return cost; }
            set { cost = value; }
        }
        public void AddOrderItem(OrderItem orderItem)
        {
            orderItems[noOrders++] = orderItem;//verify if the array is not full before save it.
            Cost += orderItem.MenuItem.MenuBaseCost;

        }


        public string GetInfo()
        {
            string result = string.Empty;
            result += "\n\t\t\t\t\tId Order : " + orderNumber + "\n";
            result += "========================================================================================";
            result += "\nDate of the order: " + this.OrderDateMade.ToString();
            result += "\t\tDate of the delivery: " + orderDateDeli.ToString();

            result += "\nDelivery Address: " + this.orderAddressDeli.streetNumber + ", ";
            result += this.orderAddressDeli.streetName + ", " + this.orderAddressDeli.city + "-";
            result += this.orderAddressDeli.province + "\n";

            result += "Orders: \n";
            foreach (OrderItem item in this.orderItems)
            {
                if (item == null)break;
                result += item.GetInfo();
            }
            result += "\n========================================================================================";
            result += "\nCost total of the order: " + this.Cost.ToString("C2");
            result += "\n========================================================================================";
            return result;
        }

    }
}

That’s the Main:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SergioS_301011342_LIB;


namespace SergioS_301011342_A1
  {
    class Program
    {
static void Main(string[] args)
        {
            OrderItem orderItem = new OrderItem(new MenuItem()
            {
                MenuName = "Hot Coffee",
                MenuDescription = "Dark Coffee with 2 milks and 2 creams",
                MenuBaseCost = 3.5M,
            });
            OrderItem orderItem2 = new OrderItem(new MenuItem()
            {
                MenuName = "Milk",
                MenuDescription = "Hot Milk",
                MenuBaseCost = 2.5M,
            });


            Customer customer1 = new Customer();
            customer1.Name = "Richard Silva";
            customer1.PhoneNumber = "6471231212";

            var address = new AddressStruct()
            {
                streetNumber = 1600,
                streetName = "Progress Avenue",
                city = "Toronto",
                province = "ON",
            };
            customer1.Address = address;


            var addressDelivery = new AddressStruct()
            {
                streetNumber = 890,
                streetName = "Keele Street",
                city = "Toronto",
                province = "ON",
            };
            var order = new Order();
            order.OrderAddressDeli = addressDelivery;
            order.AddOrderItem(orderItem);order.OrderItems[0] = orderItem;
            order.AddOrderItem(orderItem2);order.OrderItems[1] = orderItem2;
            customer1.Orders[0] = order;

            order.OrderDateMade = new DateTime();
            order.OrderDateDeli = new DateTime();


            Console.WriteLine(customer1.GetInfo());

            Console.ReadLine();


        }

2 answers

5


If you don’t use the value somehow that’s not a Setter.

In fact the original code is full of conceptual problems.

Nor will I comment on the name of namespace SergioS_301011342_LIB, he just scares me :)

It seems to me that the constructor is being used mistakenly. First of all what is there should be initialized properties, but most likely it should actually have a constructor with the required object data. This way the object doesn’t even make sense to exist because it can be created invalid. It seems to apply to all constructors.

And it’s allowing initialization of things that are very easy to make mistakes, it should have another control over the initialization of almost everything, especially these loose texts, this can’t be right.

It seems that the getters and setters there are why was cake recipe followed. Ever wondered if you really need it? Should it be so? Search here on the site, there is a lot of information about their abuse.

Catch OrderItens looks like abstraction leak.

Ideally you should only use auto-implemented properties. See below links on the subject.

The way you are building the text is quite inadequate. See Which means the "@" sign on C#? and What does the symbol "$" mean before a string?, and mainly Why should I use the Stringbuilder class instead of the String class?.

Then you have to ask yourself, can the request when created have its date changed? If you can’t, you should do something like this:

public DateTime OrderDateDeli { get; } = DateTime.Today;

If it can be changed, can it be done indiscriminately? Probably not, then it would be something like this:

public DateTime OrderDateDeli {
    get => orderDateDeli;
    set {
        //faz aqui o tratamento necessário com o value para poder usar corretamente
    }
}

And now you need to do the initialization in the constructor, there is no way, the facilitator only exists when the property is self implemented. Just do orderDateDeli = DateTime.Today; in the builder.

Only if you have no restriction you can do so (but without restriction seems wrong):

public DateTime OrderDateDeli { get; set; } = DateTime.Today;

I put in the Github for future reference.

Be wary of someone asking not to use the implemented self when it is the proper one, it teaches nothing. Use an implemented where it needs to correctly teaches the same thing as manual doing what can be implemented self.

See more:

3

public DateTime OrderDateDeli
{
    get { return orderDateDeli; }
    set { orderDateMade = DateTime.Today; } // está orderDateMade em vez de orderDateDeli
}

From C # 3.0, the properties resource has been implemented self-applied.

Through the self-applied properties we can make the statement of the properties of a class in a more concise manner when no additional logic is required in the advisors (get and set) of estates.

Source: macoratti

Example:

public DateTime OrderDateDeli { get; set; }

In C# 6 and later versions, it is possible to initialize the properties implemented in the same way as the fields:

public DateTime OrderDateDeli { get; set; } = DateTime.Today;
  • I understood, but my teacher is so boring ( to the point of giving a test to be done on no Notepad instead of Visual Studio) so he banned the use of self-applied properties. He said that once we learn how it’s done, we can use the self-applied.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.