Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 10: Date Selection – Day, Month, Year

Lesson 11 of 14 in the free C# Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Aim

To accept a date from the user, decompose it into day, month and year components, and map the identical logic onto a WinForms MonthCalendar control feeding three TextBox fields.

Theory

DateTime is a struct (value type) that packs an entire date-time into a single 64-bit field: 62 bits of ticks (1 tick = 100 nanoseconds elapsed since 0001-01-01) plus 2 bits of DateTimeKind. Properties such as .Day, .Month and .Year are not stored fields — they are computed on demand from the tick count by calendar arithmetic, which is why a DateTime occupies only 8 bytes. Parsing is culture-sensitive: DateTime.TryParse honours the current culture and reports failure through a bool return plus an out parameter instead of throwing — the TryParse pattern is .NET's idiomatic non-throwing validation and is orders of magnitude cheaper than catching FormatException in a loop. When a wire format is fixed by contract, DateTime.TryParseExact with "yyyy-MM-dd" and CultureInfo.InvariantCulture is the deterministic choice. The WinForms half is event-driven programming: MonthCalendar raises DateChanged, whose DateRangeEventArgs e exposes e.Start; the console program prints the exact subscription lambda you would place in a Forms project. A plain console app cannot host controls because it runs no Windows message loop (Application.Run) — which is why this practical ships as a console equivalent plus the wiring recipe.

Requirements

  • .NET SDK 8.0+ for the console version (dotnet new console).
  • For the GUI variant: Windows with dotnet new winforms -n DatePicker, or Visual Studio 2022 with the ".NET desktop development" workload.

Procedure

  1. Create the project: dotnet new console -n DateParts, cd DateParts, paste the code, run dotnet run.
  2. Enter 2026-07-03 (ISO yyyy-MM-dd) and record the four decomposed fields.
  3. Enter nonsense ("hello") and observe the graceful fallback to today's date instead of a crash.
  4. GUI extension: scaffold dotnet new winforms, drop a MonthCalendar and three TextBox controls onto the form, and paste the printed event-handler lambda into the form's constructor.

Explanation of the Code

  • Console.ReadLine() ?? DateTime.Today.ToString("yyyy-MM-dd") — the null-coalescing operator substitutes today's ISO string when the input stream is closed (returns null).
  • if (!DateTime.TryParse(input, out DateTime date)) — C# 7 inline out variable declaration; on failure the program logs a message and assigns DateTime.Today: validation without exceptions.
  • date.Day, date.Month, date.Year — computed properties decoding the tick count; date.ToString("MMMM") applies a format specifier for the full month name (culture-sensitive); date.DayOfWeek returns a value of the DayOfWeek enum.
  • The final Console.WriteLine block prints the WinForms wiring: monthCalendar.DateChanged += (_, e) => { ... } — a lambda subscribed to the event, with the discard _ ignoring the unused sender argument, copying e.Start.Day/Month/Year into the three text boxes.

Expected Output

For input 2026-07-03:

=== Date Selection Demo ===
Enter a date (yyyy-MM-dd): 2026-07-03

Day   : 3
Month : 7  (July)
Year  : 2026
Day of Week : Friday

WinForms equivalent:
  monthCalendar.DateChanged += (_, e) => {
      dayBox.Text   = e.Start.Day.ToString();
      monthBox.Text = e.Start.Month.ToString();
      yearBox.Text  = e.Start.Year.ToString();
  };

🎯 Viva Questions

  1. Why TryParse instead of Parse? — It signals failure via a bool instead of a costly FormatException; ideal for user input loops.
  2. Is DateTime a class? — No, a struct (value type) storing 64 bits: tick count plus DateTimeKind.
  3. What is one tick? — 100 nanoseconds, counted from 0001-01-01 00:00.
  4. What does the ?? operator do? — Null-coalescing: yields the left operand unless it is null, otherwise the right.
  5. Which event does MonthCalendar raise on selection?DateChanged, carrying DateRangeEventArgs with e.Start and e.End.
  6. Why can a console app not show WinForms controls? — It runs no Windows message loop (Application.Run) and no STA UI thread is configured.