Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# how to check if var contains constructor Params

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}";
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading