Hi
I want to know, can structure have constructor in C# ? If yes then please explain with an example anyone ?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jignesh TrivediRank #16 · 50.3K reputationPosted Apr 4, 2012, 7:27 PM EDT
yes structure is also contain constructor.
Example:
struct mystruct
{
private int value1;
public mystruct(int myValue)
{
value1 = myValue;
}
public void display()
{
System.Console.WriteLine("value=" + value1);
}
}
class testClass
{
public static void Main()
{
mystruct t = new mystruct(333);
t.display();
}
}
hope this help.
SenthilkumarRank #387 · 6.5K reputationPosted Apr 4, 2012, 7:44 PM EDT
The structure allows to create the constructor like in class. But it will not allow to create the destructor.
The syntax of the structure with constructor.
public struct MyStruct
{
int x, int y;
public MyStruct(int x, int y)
{
this.x = x;
this.y = y;
}
}
Constructor overloading:
At the same time struct allows to do constructor overloading like in classes.
It can't return any value.
public struct MyStruct
{
int x, int y;
public MyStruct(int x, int y)
{
this.x = x;
this.y = y;
}
public MyStruct(int x)
{
this.x = x;
}
}
For more info:
http://msdn.microsoft.com/en-us/library/ah19swz4(v=vs.71).aspx
VulpesRank #55 · 29.2K reputationPosted Apr 5, 2012, 2:45 AM EDT
In fact, there is one situation where you have to.
Consider, the following program which (surprisingly) doesn't compile:
using System;
However, if you change the constructor declaration to:
public MyStruct(int x, int y) : this()
then it compiles and runs fine.
The reason is that the compiler automatically produces backing fields for the 'automatic' properties X and Y.
However, you're not allowed to access any instance members of a struct (including X and Y) until all its fields have been initialized by the constructor. The only way to do this is to chain to the struct's default parameterless constructor which sets all bytes of every field to zero.