Information Technology Reference
In-Depth Information
You can also create an instance of a struct without using the
new
operator. If you do this,
however, there are several restrictions—you
cannot
Use the value of a data member until you have explicitly set it
Ca l
any
function member until
all
the data members have been assigned
For example, the following code shows two instances of struct
Simple
created without
using the
new
operator. When there is an attempt to access
s1
without explicitly setting the data
member values, the compiler produces an error message. There are no problems reading from
s2
after assigning values to its members.
struct Simple
{
public int x;
public int y;
}
class Program
{
static void Main()
{
No constructor calls
↓
Simple s1, s2;
Console.WriteLine("{0},{1}",
s1.x
,
s1.y
); // Compiler error
↑
↑
Not yet assigned
s2.x = 5;
s2.y = 10;
Console.WriteLine("{0},{1}", s2.x, s2.y); // OK
}
}