Kehan
KeTechy

KeTechy

Is { get; set; } good for all developers in C#?

Is { get; set; } good for all developers in C#?

Kehan's photo
Kehan
·Nov 5, 2022·

2 min read

Recently, I have been working on a C# project development. I deeply got the efficiency and convenience that C# wants to bring to develpers. During the time, I suddenly realized one thing at a moment, is this really good for all developers?

Then I will explain why I don't think { get; set; } is good for all developers, and talk about what do I think about code simplification in C#. Let’s start by looking at the following three pieces of code:

public class Person
{
    private string _firstName;
    private string _lastName;

    public string getFirstName()
    {
        return _firstName;
    }
    public void setFirstName(string firstName)
    {
        _firstName = firstName;
    }
    public string getLastName()
    {
        return _lastName;
    }
    public void setLastName(string lastName)
    {
        _lastName = lastName;
    }
}
public class Person
{
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }
}
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

From the above codes, you could see that they all the same thing, which is to declare two properties. However, their lines of code are different. I agree with that this is a thing to improve development efficiency, but I think that keep simplifying without a bottom might be toxic.

As programming beginners who consider C# as their first language, it is difficult for them to understand the encapsulation in Object Oriented Programming from the 3rd code. Compared to the 1st code, the 3rd code does not directly express the relationship between the data accessors and fields.

I don't think all C# code simplifications are senseless. So I recommend the 2nd code for beginners in C# programming, it not only reduces the number of lines of code, but also expresses clearly.

I am not against C# code simplifications, I just think some code simplifications are overkill. Endless code simplification could be counterproductive.

What do you think? Please write your thoughts in the comment section below.

 
Share this