Author Topic: Playing with : Primary Constructors  (Read 564 times)

0 Members and 1 Guest are viewing this topic.

kdub_nz

  • Mesozoic keyThumper
  • SuperMod
  • Water Moccasin
  • Posts: 2133
  • class keyThumper<T>:ILazy<T>
Playing with : Primary Constructors
« on: December 30, 2023, 03:31:00 PM »
I really like these, particularly when combined with some of the new syntactic sugar

Code - C#: [Select]
  1. Console.WriteLine("Hello, CS12_Playing : PrimaryConstructor");
  2.  
  3. Product p = new(1024, "Thingie");
  4. Console.WriteLine(p);
  5.  
  6. Product p2 = new(1025, "Thingie.v2", "New super Thingie");
  7. Console.WriteLine(p2);
  8.  
  9. Product p6 = new(1026, null);
  10. Console.WriteLine(p6);
  11.  
  12. Product p7 = new(1027, "", "weird prototype");
  13. Console.WriteLine(p7);
  14.  
  15.  
  16. public class Product(int id, string? name, string description = "no description")
  17. {
  18.    public int Id { get { return id; } }
  19.  
  20.    public string Name
  21.    {
  22.       get;
  23.       set;
  24.    } = (name is null || name == string.Empty) ? "no Name provided" : name;
  25.  
  26.    public string Description { get; set; } = description;
  27.  
  28.  
  29.    public override string ToString()
  30.    {
  31.       return $"Product: {this.Id}, {this.Name}, {this.Description} ";
  32.    }
  33. }
  34.  
  35.  

No Constructor required when parameters added to newed class instance.

Called Kerry in my other life
Retired; but they dragged me back in !

I live at UTC + 13.00

---
some people complain about loading the dishwasher.
Sometimes the question is more important than the answer.

kdub_nz

  • Mesozoic keyThumper
  • SuperMod
  • Water Moccasin
  • Posts: 2133
  • class keyThumper<T>:ILazy<T>
Re: Playing with : Primary Constructors
« Reply #1 on: December 30, 2023, 03:53:15 PM »
The warning ;
Message   CA1050   Declare types in namespaces   PrimaryConst   

https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1050

is because I've used the new-console-template which does not define a namespace by default when there are NO top level statements.
Called Kerry in my other life
Retired; but they dragged me back in !

I live at UTC + 13.00

---
some people complain about loading the dishwasher.
Sometimes the question is more important than the answer.