Get the App
SLTechnology News&Howtos  ›  Development  › 

How to initialize objects and collections in C # 3.0

Shulou Source: shulou.com Published: 2022-06-02 08:38:20 10月01日 Update

This article mainly explains "how to realize C#3.0 object and collection initialization". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian to study and learn "how to realize C#3.0 object and collection initialization" together.

Point class

public class Point { public int X { get; set; } public int Y { get; set; } }

Object class initialization can be defined as follows

Point p = new Point { X = 3, Y = 99 };

If it is a collection initialization, it mainly inherits System.Collections.Generic.IEnumerable

< T>

And there is a common method Add that initializes the collection.

An example of collection initialization is as follows

List

< Point>

Square = new List

< Point>

{ new Point { X=0, Y=5 }, new Point { X=5, Y=5 }, new Point { X=5, Y=0 }, new Point { X=0, Y=0 } };

Complete example source code

class Program { static List

< Customer>

CreateCustomers() { return new List

< Customer>

{ new Customer(1) { Name = "Alex Roland", City = "Berlin" }, new Customer(2) { Name = "Oliver Cox", City = "Marseille" }, new Customer(3) { Name = "Maurice Taylor", City = "London" }, new Customer(4) { Name = "Phil Gibbins", City = "London" }, new Customer(5) { Name = "Tony Madigan", City = "Torino" }, new Customer(6) { Name = "Elizabeth A. Andersen", City = "Portland" }, new Customer(7) { Name = "Justin Thorp", City = "London" }, new Customer(8) { Name = "Bryn Paul Dunton", City = "Portland" } }; } static void Main(string[] args) { List

< Customer>

customers = CreateCustomers(); Console.WriteLine("Customers:\n"); foreach (Customer c in customers) Console.WriteLine(c); } Thank you for reading, the above is the content of "C#3.0 object and collection initialization how to achieve", after the study of this article, I believe that everyone has a deeper understanding of how to achieve C#3.0 object and collection initialization, and the specific use needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Objects Clearing learning examples content that is ideas situations articles methods more source code knowledge knowledge points articles follow questions A. practice push Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info Redmi Huawei Microsoft