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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Apr 4, 2012, 11:27 PM
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.
VulpesPosted Apr 5, 2012, 6:45 AM
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.
SenthilkumarPosted Apr 4, 2012, 11:44 PM
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