Home > Net >  C# how to check if var contains constructor Params
C# how to check if var contains constructor Params

Time:12-07

using System;

namespace Exercise_7
{
    public class Dog
    {
        public string Name;
        public string Sex;
        public string Father;
        public string Mother;

        public Dog(string name, string sex)
        {
            Name = name;
            Sex = sex;
        }

        public Dog(string name, string sex, string father, string mother)
        {
            Father = father;
            Mother = mother;
            Name = name;
            Sex = sex;
        }

       public string DogsOverall()
        {
            return $"Name {Name}, sex{Sex}, fathers name is {Father}, mothers name is {Mother}";
        }

Basically, there is some vars that does not contain Father or Mother, so how can i check that? or like how to i print instead of nothing - "unknown"?

CodePudding user response:

You can call the second constructor from your first one and pass in "unknown" for example.

You can also use the ?? operator to use a fallback value when/if father/mother is null.

namespace Exercise_7
{
    public class Dog
    {
        public string Name;
        public string Sex;
        public string Father;
        public string Mother;

        public Dog(string name, string sex) : this(name, sex, "unknown", "unknown")
        {
        }

        public Dog(string name, string sex, string father, string mother)
        {
            Father = father ?? "unknown";
            Mother = mother ?? "unknown";
            Name = name;
            Sex = sex;
        }

   public string DogsOverall()
    {
        return $"Name {Name}, sex{Sex}, fathers name is {Father}, mothers name is {Mother}";
    }

CodePudding user response:

how do i print instead of nothing - "unknown"?

You can use the null-coalescing operator

public string DogsOverall()
{
    return $"Name {Name ??  "unknown"}, sex{Sex ??  "unknown"}, fathers name is {Father ??  "unknown"}, mothers name is {Mother ??  "unknown"}";
}

CodePudding user response:

for better constructors you can edit to this

public Dog(string name, string sex)
        {
            Name = name;
            Sex = sex;
        }

        public Dog(string name, string sex, string father, string mother):this(name,sex)
        {
            Father = father;
            Mother = mother;
        }

and in DogOverall you can check any prop beafor print

  •  Tags:  
  • c#
  • Related