Use Constructor to initialize member fields - CSharp Custom Type

CSharp examples for Custom Type:Constructor

Description

Use Constructor to initialize member fields

Demo Code

using static System.Console;
using System;//  w  w w .j a v a  2  s  .c om
using System.Collections.Generic;
class Program
{
   static void Main(string[] args)
   {
      var p3 = new Person();
      WriteLine($"{p3.Name} was instantiated at  {p3.Instantiated:hh:mm:ss} on {p3.Instantiated:dddd, d MMMM  yyyy}");
      var p4 = new Person("Aziz");
      WriteLine($"{p4.Name} was instantiated at {p4.Instantiated:hh:mm:ss} on {p4.Instantiated:dddd, d MMMM yyyy}");
      WriteLine(p3.GetOrigin());
   }
}
public class Person : object
{
   public string Name;
   public DateTime DateOfBirth;
   public List<Person> Children = new List<Person>();
   public readonly DateTime Instantiated;
   public const string Species = "Programmer";
   public readonly string HomePlanet = "Earth";
   public Person()
   {
      // set default values for fields
      // including read-only fields
      Name = "Unknown";
      Instantiated = DateTime.Now;
   }
   public Person(string initialName)
   {
      Name = initialName;
      Instantiated = DateTime.Now;
   }
   public string GetOrigin()
   {
      return $"{Name} was born on {HomePlanet}";
   }
}

Result


Related Tutorials