Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com
Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/
Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/
C# structs cannot have a default constructor. Writing a default parameter-less constructor would not compile, since there is one already predefined by the compiler.
For example, the following code would result in the compilation error, 'Structs cannot contain explicit parameterless constructors' :
public struct Employee
public int EmpNo;
public string LastName;
public string FirstName;
public DateTime HiredDate;
public bool IsActive;
public Employee() {
EmpNo = 0;
LastName= null;
FirstName=null;
HiredDate = new DateTime(1,1,1);
IsActive = false; }
}
The predefined constructor initializes all the members of the struct with its default values according to their types. For example, it initializes numeric types (int, long, float etc) to 0, bool types to false, reference types to null and datetime types to 1/1/0001 12:00:00 AM.
The struct variables are usually declared and used without the new operator since struct is a value type. For example:
public struct Employee
{
public int EmpNo;
public string LastName;
public string FirstName;
public DateTime HiredDate;
public bool IsActive;}
Employee emp;
emp.EmpNo = 0;
But to initialize the members with the default values, call the predefined default constructor using the new operator as follows:
emp = new Employee();
The above code initailizes EmpNo to 0, LastName and FirstName to null, HiredDate to 1/1/0001 12:00:00 AM and IsActive to false
An another way to initializes the struct members to their default values, is to use default keyword as follows:
emp = default(Employee);
Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com
No comments:
Post a Comment