Object Initializers Versus Optional Parameters - CSharp Custom Type

CSharp examples for Custom Type:Object Initializer

Introduction

Instead of using object initializers, we could make Animal's constructor accept optional parameters:


public class Animal
{
  public string Name;
  public bool LikesCarrots;
  public bool LikesHumans;

  public Animal () {}
  public Animal (string n) { Name = n; }
   public Animal (string name,
                 bool likesCarrots = false,
                 bool likesHumans = false)
   {
     Name = name;
     LikesCarrots = likesCarrots;
     LikesHumans = likesHumans;
   }

 }
      

This would allow us to construct a Animal as follows:

Animal b1 = new Animal (name: "Bo",likesCarrots: true);

Related Tutorials