Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFriso Mosselmans
2,105 PointsHow can I see what type of method "System.DateTime.DaysInMonth()" is? static or instance?
I really don't understand in this quiz why "System.DateTime.DaysInMonth()" is a static method, while "System.DateTime.AddDays()" is an instance method? There is no difference in the way they are called, is there? So how can you tell?
3 Answers
Eduardo Parra San Jose
12,579 PointsHi,
One way to know if a method is static or not is too look in the MSDN documentation:
- System.DateTime.DaysInMonth is a static method
- System.DateTime.AddDays is an instance method
The difference between them is that you can call System.DateTime.DaysInMonth static method, directly from the class, without creating an object:
// The example is from the MSDN documentation for System.DateTime.DaysInMonth
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
However, to call System.DateTime.AddDays you have to create an object of the type DateTime:
// The example is from the MSDN documentation for System.DateTime.AddDays
DateTime today = DateTime.Now;
DateTime answer = today.AddDays(36);
I hope it helps. Have a nice day
Steven Parker
231,248 PointsThe difference is clearly indicated in the documentation.
If you look at the documentation pages for System.DateTime.DaysInMonth() and System.DateTime.AddDays() , you can clearly see that the first is defined as "static", while the second is not.
As to why these are implemented differently, you can see that DaysInMonth takes two integer arguments and returns another integer. Since it makes no direct reference to a DateTime object, it makes sense that it would be implemented as static so it can be invoked without requiring a DateTime instance.
On the other hand, since the purpose of AddDays is to modify an existing DateTime object, it must have a reference to a DateTime object instance. So it makes sense that it would be implemented as an instance method.
There is, in fact, a significant difference in the way these are called. Check the documentation pages for examples.
Friso Mosselmans
2,105 PointsThank you both for these great answers!