June 3, 2007
Novice Problem
Hi Guys
I got the following program from the website. Address is given. I couldn’t understand following statements. Please anybody explain.
public Time1(System.DateTime dt)
1) Normally in the parentheses built-in data type and variable must come instead System.DateTime dt is coming. Please explain.
System.DateTime currentTime = System.DateTime.Now;
2) I couldn’t understand above one at all. Please explain.
Thank you
//Method overloading test
//http://www.java2s.com/Code/CSharp/Language-Basics/Methodoverloadingtest.htm
using System;
namespace MethodOverloading
{
public class Time1
{
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// public accessor methods
public void DisplayCurrentTime()
{
Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
Month, Date, Year, Hour, Minute, Second);
}
// constructors
public Time1(System.DateTime dt) //???????????????????
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
public Time1(int Year, int Month, int Date,
int Hour, int Minute, int Second)
{
this.Year = Year;
this.Month = Month;
this.Date = Date;
this.Hour = Hour;
this.Minute = Minute;
this.Second = Second;
}
}
public class MethodOverloadingTester
{
public void Run()
{
System.DateTime currentTime = System.DateTime.Now; //????????????????
Time1 time1 = new Time1(currentTime);
time1.DisplayCurrentTime();
Time1 time2 = new Time1(2000,11,18,11,03,30);
time2.DisplayCurrentTime();
}
static void
{
MethodOverloadingTester t = new MethodOverloadingTester();
t.Run();
}
}
}
Posted Jun 3, 2007, 11:08 AM
AlanPosted Jun 3, 2007, 10:58 AM
Methods or constructors in C# can in fact accept any type of parameter, not just built-in types.
System.DateTime is a struct in the .NET framework which (as its name suggests) represents a date and time. As you already have the directive 'using System' in your program, you could in fact shorten the name to just DateTime.
In the following statement:
System.DateTime currentTime = System.DateTime.Now;
which could be abbreviated to:
DateTime currentTime = DateTime.Now;
a variable called 'currentTime' is being declared of the DateTime type.
This variable is then being assigned the value of the static property 'Now' of the DateTime struct which represents the current date and time.