Do I need to use a field if there is a property?

vitaminchik 486 Reputation points
2023-02-25T18:40:39.8633333+00:00

I recently studied the topic of property in programming. I began to practice and I had a question. Is it necessary to use a field if there is a property?I've seen other people's code. They only used properties.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Craig Williams 75 Reputation points
    2023-02-25T20:01:16.25+00:00

    It is not strictly necessary, but it is generally considered good design practice to only use public properties when you need to expose data outside of the class. For use within a class a private field member will suffice, and the property exposes the private field member. Using the different naming conventions within your class allows you to know at a glance that it is the private member variable.

    There are scenarios when you might want to consider using a private property as well as a private field within a class, such as when lazy loading cached values.

    https://stackoverflow.com/questions/3310186/are-there-any-reasons-to-use-private-properties-in-c

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-02-25T23:49:21.37+00:00

    if you define a property like:

    public string MyProperty {get; set;}

    the compiler will generate a backing field for you. if you need access to the backing field, then you can name it. while its slight faster to access the backing field directly rather than via the getter, it is not that important. a backfield is generally required when you want a customer getter or setter.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.