0

I have something similar to the following very simple code, but I'm getting caught out by the way objects are referenced. I'd like to understand what's going on a little more.

I'm surprised to find that _connection.Name and _connection.Enabled can be modified outside of the class.

internal class ConnectionProperties
{
    internal string Name = "Default Name";
    internal bool Enabled = true;
}

internal class Data
{
    private readonly ConnectionProperties _connection;
    internal string ConnectioName => _connection.Name;

    internal ConnectionProperties Connection()
    {
        return _connection;
    }

    internal Data()
    {
        this._connection = new ConnectionProperties();
    }

}


class Program
{
    static void Main(string[] args)
    {
        Data data = new Data();

        Console.WriteLine(data.ConnectioName);

        ConnectionProperties temp = data.Connection();
        temp.Name = "New Name";

        Console.WriteLine(data.ConnectioName);

    }
}

OUTPUT:

Default

Name New Name

Dan
  • 1,958
  • 1
  • 18
  • 26
  • @Stefan Yes I have, that's the only reason I'm asking. The above code is a very simplified form of my testing. Perhaps I should create a new Proof of Concept and copy the code verbatim – Dan Jan 04 '20 at 14:56
  • `data.Connection()` doesn't magically give you a new instance of `ConnectionProperties`. A new instance is only created when you write `new ConnectionProperties()`. – Sweeper Jan 04 '20 at 14:56
  • @Sweeper I know, let's pretend Data has a constructor which sorts that – Dan Jan 04 '20 at 14:56
  • On a second reading, are you mixing up `internal` and `private`? – Sweeper Jan 04 '20 at 14:57
  • 1
    Why are you surprised? Internal can be modified out of the class, what you want is private! – panoskarajohn Jan 04 '20 at 14:59
  • @Dan Well, you only called `new Data()` once as well, so either way there's not going to be 2 instance of `ConnectionProperties`, even if the constructor of `Data` calls `new ConnectionProperties` – Sweeper Jan 04 '20 at 14:59
  • @Dan: your edit is crucial for the question; now your conclusion is correct again ;-) – Stefan Jan 04 '20 at 14:59
  • @panoskarajohn I am surprised as I don't fully understand the mechanism! – Dan Jan 04 '20 at 15:05
  • I've created a new console app and copied the code and output, would really appreciate if somebody could explain what's happening behind the scenes – Dan Jan 04 '20 at 15:05
  • Add a new startup project to this solution and try accessing the class from there. – LarsTech Jan 04 '20 at 15:13
  • @Dan please tale a look here https://stackoverflow.com/questions/3813485/internal-vs-private-access-modifiers – panoskarajohn Jan 04 '20 at 15:18

0 Answers0