Deryl
Deryl

Reputation: 66

How to count initialized fields in C# method?

My class is like:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Nickname{ get; set; }

    public Person GetPersonData()
    {
        return new Person()
        {
            Name = "Chris",
            Surname = "Topher"
        };
    }
}

How can I count elements in GetPersonData() method? I was using GetProperties a bit, but then, when I have some more methods with initialization of others variables, then it does not work as i would like to. I need to get exact number of elements there. Thank you for any help!

Upvotes: 0

Views: 258

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38850

If you simply want to know if the properties have been assigned, you could use a pattern like this:

public class Person
{
    private string _name;
    private string _surname;
    private string _nickname;

    public string Name { get => _name; set { _name = value; NameInitialized = true; } }
    public bool NameInitialized { get; private set; }
    public string Surname { get => _surname; set { _surname = value; SurnameInitialized = true; } }
    public bool SurnameInitialized { get; private set; }
    public string Nickname { get => _nickname; set { Nic _nickname = value; NicknameInitialized = true; } }
    public bool NicknameInitialized { get; private set; }

    public Person GetPersonData()
    {
        return new Person()
        {
            Name = "Chris",
            Surname = "Topher"
        };
    }
}

Basically, when you assign a value via the setter, it will set the corresponding boolean property to true. Of course, you could still set Nickname = default(string); and then it would still be counted as "initialized", but I think this solution may solve your problem.

You could also make use of CallerMemberName to get the property name and update a dictionary, for example.

public class Person
{
    private string _name;

    private void SetInitialized([CallerMemberName]string propertyName = "")
    {
        // update a dictionary
    }

    public string Name { get => _name; set { _name = value; SetInitialized(); } }
}

Nullable reference types could also be useful (but that's a feature planned for C# 8).

Upvotes: 1

Related Questions