O
O
Oksana Volovik2014-10-03 12:05:14
C++ / C#
Oksana Volovik, 2014-10-03 12:05:14

How to allow changing fields and creating an instance of a class, only one control class?

There is a simple class with a few read-only fields:

class Item
    {
        readonly string name;
        readonly int id;

        public Item ( string _name , int _id )
        {
            name = _name;
            id = _id;
        }
    }

How to make a control class that will be allowed to change fields and create instances of the Item class?
Or how to prevent other classes except the manager from changing the fields of the Item class and creating an instance of it?
PS In this case, Item is a class, but this is just for the sake of an example, it can also be a structure, which is more logical.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Mozhaykin, 2014-10-03
@tirenta

The nested class option works:

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Item.ItemManager manager = new Item.ItemManager();
            //Item i = new Item("name", 0); //'TestApp.Item' does not contain a constructor that takes 2 arguments
            Item i1 = manager.CreateItem("item", 1);
            Console.WriteLine(i1); //Output: "Item id=1, name=item"
            //i1.Id = 2; //The property or indexer 'TestApp.Item.Id' cannot be used in this context because the set accessor is inaccessible
            //i1.Name = "item1"; //The property or indexer 'TestApp.Item.Name' cannot be used in this context because the set accessor is inaccessible
            manager.ChangeId(i1, 2);
            manager.ChangeName(i1, "item1");
            Console.WriteLine(i1); //Output: "Item id=2, name=item1"
            Console.ReadLine();
        }
    }


    
    public class Item
    {
        public string Name { get; private set; }
        public int Id { get; private set; }
        
        private Item(string _name, int _id)
        {
            Name = _name;
            Id = _id;
        }

        public override string ToString()
        {
            return string.Format("Item id={0}, name={1}", Id, Name);
        }
        
        public class ItemManager
        {
            public Item CreateItem(string name, int id)
            {
                return new Item(name, id);
            }

            public void ChangeName(Item item, string newName)
            {
                item.Name = newName;
            }

            public void ChangeId(Item item, int newId)
            {
                item.Id = newId;
            }
        }
    }
}

And if you do decide to use mutable structures, be careful with them.

B
bmforce, 2014-10-03
@bmforce

You can use the internal access modifier.
msdn.microsoft.com/en-us/library/7c5ka91b.aspx

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question