-1

It is possible using new object field as function parameter other field (in this same object initialization)?

List<Reservations> reservations = new List<Reservations>()
 {
  new Reservations{title="Grooming", className=checkColor(title)},
 };

public string checkColor(string title)
{
 ...
}         
poke
  • 369,085
  • 72
  • 557
  • 602
Adam Wróbel
  • 344
  • 6
  • 25
  • I don't think so. you have to use className=checkColor("Grooming") Why you just have not checked it immedialtely instead of waisting time of another people? – Serge Jan 02 '21 at 17:02
  • 2
    No, you cannot reference an object from within that object’s object initializer. You should consider using a constructor or a factory method instead if you need to run additional logic. – poke Jan 02 '21 at 17:13

1 Answers1

0

It isn't possible with the current design of your code. The reason is, you can not reference 1 field of the object in another field before the object is fully constructed. That is same as why we can't use 1 field value in another while declaring as class level varibales.

However, there are ways you can achieve, what you want to.

Option 1:

const string titleText = "Grooming";
List<Reservations> reservations = new List<Reservations>()
{
    new Reservations{title=titleText, className=checkColor(titleText)},
};

private static string checkColor(string title)
{
 ...
}

Option 2:

    class Consumer
    {
        List<Reservations> reservations = new List<Reservations>()
        {
            new Reservations{title="Grooming"}
        };
    }

    class Reservations
    {
        string _title;

        public string title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
                className = checkColor(title);
            }
        }

        public string className;

        private string checkColor(string title)
        {
            return "";
        }
    }
Sisir
  • 4,584
  • 4
  • 26
  • 37