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 trial

C# C# Objects Methods Documentation

Why is System.DateTime.DaysInMonth() static and System.DateTime.AddDays() instance? Same same to me.

I can´t see any difference between these two.

// Jimmy

Ok sorry, offcourse google had the answer but still i guess there is no way you can tell by just looking at the two methods? To me both are called directly on the class, just like they say static methods are... Would really like an explanation ;)

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! The biggest difference (as far as I know) is that the static method can be called directly on the class. The instance method requires that you first construct an instance of the object and then call the method on it.

So you could, for example, use the DaysInMonth without ever creating an instance of the DateTime class. However, to use AddDays, you must first create an instance of DateTime somewhere else in your code.

Hope this helps! :sparkles:

Yes it does. Thank you very much!

Daniel W
Daniel W
1,341 Points

When looking at function, there's really no way to tell if it's static or not without looking it up. You could logically reason by looking at the name of the funciton. If we had a thermometer class, the method FahrenheitToCelsius() would likely be static. While something like AddTemperature(int c) would logically require a thermometer object. If such a method was static, the temperature variable would have to be static, and thus the value would be shared for ALL thermometers.

Here, AddDays() looks to need an object just judging by the name alone. Remember that the class name is to the left of the dot, and everything before that is the namespace where it lives. Thus it's easy to both search online, or type out the namespace and class to see what static methods are suggested by your IDE.

The Math class as you can imagine has pretty many static methods, since an object or it's state doesn't need to change.