Arlen Beiler
Arlen Beiler

Reputation: 15866

How to specify the get/set internal var in a property in C#

Is there a way to specify the private field to store a public get value in? Or is that really pointless. Something like this:

private int _myint = 5;
public int MyInt { get(ref _myint); }

Obviously the current method is:

public in MyInt { get; private set; }

But that doesn't let you access the backing store. I don't know, maybe this doesn't even have a use case, but I thought I'd ask.

Upvotes: 1

Views: 66

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564373

You just need to not use the automatic properties:

private int _myint = 5;
public int MyInt 
{ 
    get { return _myint; }
    private set { _myint = value; }
}

The automatic properties just provide a shorter, more convenient syntax where the compiler creates and names the backing field for you.

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40393

You'd just do a traditional property at that point:

private int _myInt;
public int MyInt { get { return _myInt; } }

// or

private int _myInt;
public int MyInt { get { return _myInt; } private set { _myInt = value; } }

The second one just means that you have a wrapper around your field which can be used inside of your class. Either way, your field can only be set from inside this class.

Upvotes: 2

Related Questions