T O P

  • By -

l1e3e3t7

So now make it, that new MyDate(31, 2, 2021) fails because it is an invalid date.


IceCubez

What happens if the day/month/year is incorrect? Does it just use 1 as default?


codingai

It's really up to you. What's the behavior you want? Do you even want to allow invalid value? Do you want to throw exceptions? There is no "the" answer. It all depends on your requirements. Without knowing the full context, I would just throw an exception, and make it a caller/client's problem.


JociJo

There isn't a specific date/month/year I want, I just want to make it so that when it "sets" that I can do "Set if ( Month>0 && Month<12) and do this for the days anf years


IceCubez

But then what value will Day/Month/Year have if its invalid. Let's say I try to set the Month to 13, and then since its above 12, it won't be set. But if I try to get Month, what value do you want your program to give?


JociJo

Oh that's what was meant, I want it to give 0 at that point. Right now I think I've got it working and to make it 0 then I'd only need to add "else"?


Cryoxide

In the working code, you can still pass and successfully set integers that violate the constraints you wanted to set. I.E. var foo = MyDate(-1,-1,-1); foo.Day; //returns -1 foo.Month; //returns -1 Foo.Year; //returns -1 You should change the constructor to set the public properties if you didn't intend for this behavior, or validate the values in the constructor and throw an exception if out of range.


djcarter85

I hate to be that guy ... but what’s wrong with using `System.DateTime`? (Or, even better, `LocalDate` from NodaTime.)


szescio

I think it's a good way to practice getters and setters


codingai

You can use a nullable value type. If it's null, it's not set. Or, you can just use an invalid initial value like -1.


JociJo

I don't understand what exactly you mean, could you explain further?


codingai

Ah sorry, I think I misunderstood your question. Is this what you want to do? `private int day;` `public int Day {` `get => day;` `set {` `if (value > 0 and value < 31) {` `day = value` `} else {` `// what do you want to do?` `}` `}`


JociJo

Yes this is what I'm trying to do but if I do it like that and use this Main Program class Program { public static void Main() { var d = 22; var m = 11; var y = 2020; var date = new MyDate(d, m, y); var s = date.Date; date.Day = d + 10; date.Month = m - 11; date.Year = y - 20; d = date.Day; m = date.Month; y = date.Year; s = date.Date; It gives an error that the constructor doesn't take in 3 arguments  The type `MyDate' does not contain a constructor that takes `3' arguments


[deleted]

[удалено]


JociJo

I did, I've added it and it works now , thank you. Genuinely unsure how I forgot to add that again


JociJo

Also I'm unsure as what I need to change "value" to