I just saw some snippet code using the struct DateTime.Today and I can't understand the inner workings of it. Here is the specific line:
if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
After using Go To Definition F12, I saw that the Today static method returns a DateTime object with the date information in your current computer. I suppose that Today method works as a constructor wrapper. What I can't deduce (more like guessing) is how it's possible to access the property DayOfWeek without instantiating first the Today struct.
Can someone explain me how is this possible? My only guess is that when VS compiles the code to IL maybe it converts this syntactic sugar to:
if ( (DateTime.Today()).DayOfWeek == DayOfWeek.Monday )
Maybe this is as clean as water but I'm a C# newbie so I just can't figure it out.
Thanks in advance!
You guest it right, welcome to the wonderful world of properties.
DateTime.Todayis a property which in short is a function generated by the compiler, it translates toDateTime.get_today(). So that expression would actually beExample:
Decompiled
GetNameDecompiled
NameDecompile
Main(method calls)As you can see there is absolutely no difference between
NameandGetNameexcept the fact thatNameis generated by the compiler for you asget_Name.Update 1
As for
DateTime.Todayit actually get transformed intoSystem.DateTime [mscorlib]System.DateTime::get_Today()What you have to understand is that even if the compiler generates those functions for you, they can't be accessed directly because it generates IL code(assembly code for .NET) not C# (things might have changed with Roslyn the new C# compiler but don't know much about that)
What i recommend, if you're really curious about what really happens in you application, is to use ildasm.exe it allows you to see the IL generated by the compiler. A nice book on the subject it called CLR via C#, i had contact with the 3rd edition but apparently there's a 4th edition now.