using System;
class MyClass {
public int Count;
public string Str;
}
class ObjInitDemo {
static void Main() {
// Construct a MyClass object by using object initializers.
MyClass obj = new MyClass { Count = 100, Str = "Testing" };
Console.WriteLine(obj.Count + " " + obj.Str);
}
}
This produces the following output:
100 Testing
As the output shows, the value of obj.Count has been initialized to 100 and the value of
obj.Str has been initialized to “Testing”. Notice, however, that MyClass does not define any
explicit constructors, and that the normal constructor syntax has not been used. Rather, obj
is created using the following line:
MyClass obj = new MyClass { Count = 100, Str = "Testing" };
No comments:
Post a Comment