Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# what does this code with "get" mean?

Tags:

c#

properties

I am new to C#.

private string m;
public string M { get { return m; } }

Is this kind of a getter/setter in C# like Java?

like image 703
David Degea Avatar asked Jan 26 '26 06:01

David Degea


2 Answers

This part is a field:

private string m;

This part is a read-only property that returns the value of the m field:

public string M { get { return m; } }

You could make this a read-write property like so:

public string M {
    get { return m; }
    set { m = value; }
}

Or you could have more complex logic in there:

public string M {
    get {
        if (string.IsNullOrEmpty(m))
            return "m is null or empty";
        return m;
    }
}

Basically, fields are only good at holding things, while properties are more like methods and can introduce logic.

like image 54
CodeNaked Avatar answered Jan 27 '26 19:01

CodeNaked


private string m;

First, you create a new string variable with private modifier. If this in class, then it's not visible outside of this class.

public string M { get { return m; } }

Then you create a property of that string variable. This property is read-only and then you can access this variable outside of class where you created this variable. You cannot assign values to this variable with this type of property.

like image 31
evilone Avatar answered Jan 27 '26 18:01

evilone



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!