I'm learning C# from the book "Head First C#". I thought I understood properties. They are used like fields but work like methods, with getters and setters. I never thought of them as another object appending to the instantiated object. Is that the case?
Please see the code given in the book and the Outfit object which got me thinking about this.
Thank you so much for your help!!
Follow-up questions:
- Is it the case that when an object is instantiated, all of its properties will also be instantiated as objects on the heap, except for the value types?
- Why isn't there a
HairStyle
object connected to theGuy
object in this case?
CodePudding user response:
Yes, you are rigth when say "property like methods", but this methods needs to work with some type, and it can be base type or object as well.
CodePudding user response:
I think it's better that we pay attention to the difference between class and object first.
Many people get confused by the difference between a class and an object. The difference is simple and conceptual. A class is a template for objects. A class defines object properties, including a valid range of values and a default value. A class also describes object behavior. An object is a member or an "instance" of a class. An object has a state in which all of its properties have values that you either explicitly define or that are defined by default settings.
And now, let's check out the properties:
Properties are attributes or features that characterize classes. While classes are groups of objects, an instance is a specific object that actually belongs to a class.
CodePudding user response:
I'm not exactly sure what you're asking but maybe this will help. The properties you're looking at are like, you said, getters and setters of a certain type (string, int, Outfit etc).
The "Full" property below is what's going on under the hood (as far as I know)
public class Props
{
//Syntactic Sugar
public string? MyProperty { get; set; }
//What's actually happening
private string? myProperty_full;//This is the field that holds the value
public string? MyProperty_Full
{
get => myProperty_full;
//value is whatever the user sets MyProperty_Full to
set => myProperty_full = value;
}
}
In the case of Clothes property. There is a private backing field of type Outfit with some getters and setters for manipulating it.