I'm new to C# and I can't find the right things to search for. I'm trying to understand the difference between these three types of syntax:
public string Topic(){}public class Topic{}public string Topic{}I know the 1st is a function and the 2nd is a class, but what confuses me is what the 3rd is.
what is #3 called and how is it used?
Anything that could provide clarity please.
The 3rd is a property. The most common representation in C# is autogenerated properties, like this:
public string Topic { get; set; }
Which is equivalent to:
private string _topic;
public string Topic
{
get { return _topic; }
set { _topic = value; }
}
It should be used to hold internal states of the object.
It can be a readonly property, with getter only:
public string Topic { get; }
Or only with setter:
public string Topic { set; }
You can also apply accessibility modificators in getters and setters, for example:
public string Topic { protected get; private set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With