The default constructor cannot be declared for the structure (a constructor without parameters ). because the compiler will always generate. in a class, the compiler will generate a default constructor only when no constructor is written by itself. in the default constructor generated by the compiler for the structure, the field is always set to 0, false, or null, which is the same as the class. however, in a self-written Constructor (again, this must be a non-default constructor), you must Initialize all fields on your own, and the compiler will not help us initialize it. this means that all fields must be explicitly initialized in all non-Default constructors of the structure; otherwise, compilation errors may occur. for example, assuming that Time is replaced by a class, the following example can be compiled and seconds will be quietly initialized to 0. however, since Time is a structure, it cannot be compiled:
Struct Time
{
Public Time (int hh, int mm)
{
Hours = hh;
Minutes = mm;
// Seconds = 0;
}
Public int hours, minutes, seconds;
}
Modify:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ConsoleApplication1
{
Class Program
{
Static void Main (string [] args)
{
Try
{
Time time0 = new Time ();
Console. WriteLine ("{0 }:{ 1 }:{ 2}", time0.hours, time0.minutes, time0.seconds );
Time time1 = new Time (6, 25 );
Console. WriteLine ("{0 }:{ 1 }:{ 2}", time1.hours, time1.minutes, time1.seconds );
}
Catch (Exception ex)
{
Console. WriteLine (ex. Message );
}
}
Struct Time
{
Public Time (int hh, int mm)
{
Hours = hh;
Minutes = mm;
Seconds = 0;
}
Public int hours, minutes, seconds;
}
}
}
If you declare Time as a class, you do not need to initialize all fields, but there is no default constructor with or without parameters. Therefore, you need to write a constructor without parameters.
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ConsoleApplication1
{
Class Program
{
Static void Main (string [] args)
{
Try
{
Time time0 = new Time ();
Console. WriteLine ("{0 }:{ 1 }:{ 2}", time0.hours, time0.minutes, time0.seconds );
Time time1 = new Time (6, 25 );
Console. WriteLine ("{0 }:{ 1 }:{ 2}", time1.hours, time1.minutes, time1.seconds );
}
Catch (Exception ex)
{
Console. WriteLine (ex. Message );
}
}
}
Class Time
{
Public Time ()
{
} // To define a constructor without parameters, it is not generated by default.
Public Time (int hh, int mm)
{
Hours = hh;
Minutes = mm;
} // You do not have to initialize all fields. The default value is 0.
Public int hours, minutes, seconds;
}
}
Author: "McDelfino"