How to declare a C# Record Type?

前端 未结 6 1555
日久生厌
日久生厌 2021-02-06 23:22

I read on a blog that C# 7 will feature record types

class studentInfo(string StudentFName, string StudentMName, string StudentLName);

However

6条回答
  •  名媛妹妹
    2021-02-07 00:01

    C#9 is now available and records with it.

    Here are some example:

    public record Person
    {
        public string LastName { get; init; }
        public string FirstName { get; init; }
    
        public Person(string first, string last) => (FirstName, LastName) = (first, last);
    }
    

    With the use of positional records (and inheritance):

    public record Teacher(string FirstName, string LastName,
        string Subject)
        : Person(FirstName, LastName);
    
    public sealed record Student(string FirstName,
        string LastName, int Level)
        : Person(FirstName, LastName);
    
    var person = new Person("Bill", "Wagner");
    
    var (first, last) = person;
    Console.WriteLine(first);
    Console.WriteLine(last);
    

    Finally, records support with-expressions. A with-expression instructs the compiler to create a copy of a record, but with specified properties modified:

    Person brother = person with { FirstName = "Paul" };
    

    Everything you need to know about every new features including records here

提交回复
热议问题