Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# brackets without function or class syntax [closed]

Tags:

syntax

c#

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:

  1. public string Topic(){}
  2. public class Topic{}
  3. 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.

question

what is #3 called and how is it used?

Anything that could provide clarity please.

like image 413
Jonathan Portorreal Avatar asked Sep 05 '26 13:09

Jonathan Portorreal


1 Answers

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; }
like image 119
Marcell Alves Avatar answered Sep 08 '26 03:09

Marcell Alves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!