C# make a class data member read only to parent?

mjeschke 40 Reputation points
2025-06-17T22:15:49.1833333+00:00

I need to make certain data members in a class read only to parent classes. I'm currently doing this to protect data. It's a LOT of duplicate code / writing...

Certainly there's a better way to do than what I'm currently doing below?

// Currently using method below...
public class example1
{	
	private int data;	
	public int Data() { return data; }
}

// Tried this but only constructor can modify value and not member functions of class.
public class example2
{		
	public int data {get;}
	public readonly int data;
}

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. David Lowndes 2,640 Reputation points MVP
    2025-06-17T22:54:13.2533333+00:00

    A more succinct way is to have a property that has a public getter and private setter:

     public int MyProp { get; private set; }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.