C# struct Constructor
In this chapter you will learn:
Default constructor
If you define a constructor for a struct you must use the constructor to initialize all fields.
using System;/* w w w .j av a 2 s . co m*/
public struct Simple {
public int i;
private string s;
public void init( ) {
i = 10;
s = "Hello";
}
}
public class MainClass {
public static void Main( ) {
Simple simple = new Simple();
simple.init( );
}
}
struct cannot have the field initializer.
The code above generates the following result.
Example 2
using System;/*from w ww .j av a 2 s . c o m*/
struct Point
{
public int x;
public int y;
public Point(int a, int b)
{
x = a;
y = b;
}
}
class MainClass
{
static void Main()
{
Point p1 = new Point();
Point p2 = new Point(5, 10);
Console.WriteLine("{0},{1}", p1.x, p1.y);
Console.WriteLine("{0},{1}", p2.x, p2.y);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
C# Structs
C# Struct Instances vs. Class Instances
C# Generic struct
C# Struct Instances vs. Class Instances
C# struct Constructor
C# struct equalityC# Generic struct