Home » New in .NET 7 [7]: Auto-Default Structs in C# 11.0

New in .NET 7 [7]: Auto-Default Structs in C# 11.0

by admin
New in .NET 7 [7]: Auto-Default Structs in C# 11.0

Prior to C# 11.0, a parameterless constructor in a structure had to explicitly assign a value to all fields and properties not initialized in the declaration, such as ID and Name in the following example:

dr Holger Schwichtenberg is Chief Technology Expert at MAXIMAGO, which offers innovation and experience-driven software development, including in highly critical safety-related areas. He is also head of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with advice and training in the development and operation of software with 38 renowned experts.

struct Experte
 {
  public int ID;
  public string Name { get; set; }
  public List Themen { get; set; } = new List(); 
 
  public List MitarbeiterTeam { get; set; } = 
    new List();

  struct Adresse
  {
   public string Strasse { get; set; }
   public string PLZ { get; set; }
   public string Ort { get; set; }
  }

  public Experte()
  {
   ID = 0;
   Name = "unbekannt";
  }

  public Experte(int id, string name)
  {
   ID = id;
   Name = name;
  }

  public int ThemenAnzahl { get { return this.Themen.Count; } }
  public string GetThemenString()
  {
   return String.Join(", ", this.Themen);
  }
 }

This has changed with C# 11.0: The data members (fields and properties) of structures no longer have to be explicitly initialized in their own constructors if they do not have initialization values ​​when they are declared.

Since C# 11.0, all fields and properties that are not explicitly initialized are initialized with their default values. Microsoft calls the feature Auto-Default Structs.


(rme)

To home page

See also  Sony's entry-level true wireless headphones have ANC new WF-C700N debut

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy