9

Bite-Size C# 10 - Semi-Auto Properties and 'field' Keyword

 2 years ago
source link: https://exceptionnotfound.net/bite-size-csharp-10-semi-auto-properties-using-field-keyword/?utm_campaign=Feed%3A+ExceptionNotFound+%28Exception+Not+Found%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Bite-Size C# 10 - Semi-Auto Properties and 'field' Keyword

Bite-Size C# 10 - Semi-Auto Properties and 'field' Keyword

Last updated 4 days ago by Matthew Jones

∙ ∙ ∙

Originally published 4 days ago ∙ 2 min read ∙ 0 comments

The next feature in our Bite-Size C# 10 series is one that could make our classes a whole lot less cluttered: semi-auto properties, using the field keyword!

Current Implementation

In C# 9.0 and below, we have the concept of auto-implemented properties:

public class Employee 
{
    public string HireDate { get; set; }
}

This is great, so long as you don't want to do any processing to any of these values during instantiation. Say, for example, that we want only the Date portion of a given DateTime object to be saved into the HireDate field. To do this, we have to use a backing property:

public class Employee
{
    private DateTime _hireDate;

    public DateTime HireDate { 
        get
        {
            return _hireDate;
        }
        set
        {
            _hireDate = value.Date;   
        }
    }
}

That's quite a bit of code for one little change!

New Implementation

In C# 10, the new field keyword can be used to replace the backing property from the previous code block. We can simplify our Employee class like so:

public class Employee
{
    public DateTime HireDate { get; set => field = value.Date; }
}

Note that if the property was declared with the init setter introduced in C# 9.0 instead of set, the field keyword will still work correctly.

public class Customer
{
    public DateTime DateOfVisit { get; init => field = value.Date; }
}

Other Considerations

At the time of writing, this feature has not been included in the 10.0 milestone from the C# team. This may mean that this feature won't actually make it into C# 10. Please keep this in mind.

Demo Project

This feature is included in my demo project for this series, however it won't compile at the moment, since semi-auto properties are not included in the C# 10 preview at publishing time.

CSharp10Features

Happy Coding!

Did you like this post? Share it!

The link has been copied!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK