Search code examples
c#scopeaccess-modifiers

How to expose internal data as readonly in a class?


I have a class with an internal struct that contains data specific to that class.

However i want other classes to be able to read the data as a read-only setup.

So i tried:

public class MyClass{
    private Data _data;
    public Data Data
    {
        get { return _data; } //expose the internal data as read only
    }

    internal struct Data
    {
        public int SomeData;
    }
}

This gave me the error:

 Inconsistent accessibility: property type

It doesn't make much sense for the Data struct to be outside of MyClass since it's only related to that class. Everything else just reads it.

What would be the correct way to do this?


Solution

  • Make your struct immutable and give that to the outside. Like this:

    public class MyClass
    {
        private Data _data;
        public Data DataToExpose
        {
            get { return _data; } //expose the internal data as read only
        }
    
        public struct Data
        {
            public Data(int someData)
            {
                this.SomeData = someData;
            }
            public int SomeData { get; }
        }
    }
    

    Now people can use the Data from outside but it will be a read-only. Both the reference and the fields are read-only. It is good practice to make structs immutable anyways.