You can use an object or collection initializer with the new operator to instantiate and initialize an object in one statement, as the following example shows:
Constructor invocation expressions are target-typed. That is, if a target type of an expression is known, you can omit a type name, as the following example shows:
Use array initialization syntax to create an array instance and populate it with elements in one statement. The following example shows various ways how you can do that:
C#
var a = newint[3] { 10, 20, 30 };
var b = newint[] { 10, 20, 30 };
var c = new[] { 10, 20, 30 };
Console.WriteLine(c.GetType()); // output: System.Int32[]
To create an instance of an anonymous type, use the new operator and object initializer syntax:
C#
var example = new { Greeting = "Hello", Name = "World" };
Console.WriteLine($"{example.Greeting}, {example.Name}!");
// Output:// Hello, World!
Destruction of type instances
You don't have to destroy earlier created type instances. Instances of both reference and value types are destroyed automatically. Instances of value types are destroyed as soon as the context that contains them is destroyed. Instances of reference types are destroyed by the garbage collector at some unspecified time after the last reference to them is removed.
For type instances that contain unmanaged resources, for example, a file handle, it's recommended to employ deterministic clean-up to ensure that the resources they contain are released as soon as possible. For more information, see the System.IDisposable API reference and the using statement article.
Operator overloadability
A user-defined type can't overload the new operator.
Μπορείτε να βρείτε την πηγή για αυτό το περιεχόμενο στο GitHub, όπου μπορείτε επίσης να δημιουργήσετε και να εξετάσετε ζητήματα και αιτήματα έλξης. Για περισσότερες πληροφορίες, ανατρέξτε στον οδηγό συνεργατών.
.NET σχόλια
.NET είναι ένα έργο ανοιχτού κώδικα. Επιλέξτε μια σύνδεση για να παρέχετε σχόλια:
Συμμετάσχετε στη σειρά meetup για να δημιουργήσετε κλιμακούμενες λύσεις AI που βασίζονται σε πραγματικές περιπτώσεις χρήσης με συναδέλφους προγραμματιστές και ειδικούς.