0

I have two classes, one ExampleClass and one ExampleClassManager, which contains a list of ExampleClass.

ExampleClass has a private _id field, which I want to set in the ExampleClassManager class. Is this possible?

public class ExampleClass
{
    //Fields
    private string _id; //Should be set in ExampleClassManager
}


public class ExampleClassManager
{
    //Fields
    List<ExampleClass> exampleClassList = new List<ExampleClass>();  
}
ono2012
  • 4,967
  • 2
  • 33
  • 42
Nungwe
  • 29
  • 6
  • 3
    Have you considered using the constructor for exampleClass to initialize iD? That way you can pass the id on creation of the class being added to the list. – Kevin Cook Feb 01 '18 at 15:13
  • 1
    If your manager class is used to create the child classes, you can pass the id in the constructor of the child. – Martin E Feb 01 '18 at 15:13

3 Answers3

5

There're several possible options.

  1. Make it public (not recommended, because it's bad)
  2. Create a public property for access
  3. Create a public method to set the value (basically the same as second option)
  4. Do it with reflection

I would prefer the second option, because I think it's the cleanes way. When you have no chance to change the modifier you will have to use the fourth option.

user743414
  • 936
  • 10
  • 23
  • 2
    Public fields are not recommended by Microsoft. Your option 2 is the definitely the cleanest approach. Perhaps all OP needs is an auto property `public string iD { get; set;}`. – Lucas Feb 01 '18 at 15:13
  • Another one would be internal if it is within the same project or an explicit interface implementation. – Oliver Feb 01 '18 at 15:14
  • What about a constructor? public fields are an awful idea by the way – maccettura Feb 01 '18 at 15:16
  • Thanx guys! Will try reflection! – Nungwe Feb 02 '18 at 12:43
0

For this you can use properties.

msdn doc

answer on stackoverflow

Maksym Labutin
  • 561
  • 1
  • 8
  • 17
0

Example 1: (like Kevin Cook says) ExampleClass takes the id in the constructor and then id can't be changed:

public class ExampleClass
{
    public class ExampleClass(string id)
    {
        _id = id;
    }

    //Fields
    private readonly string _id; //note the use of **readonly**
    public string Id { get {return _id; } } //So ExampleClassManager can see the id
}

usage:

var actualObject = new ExampleClass("abc123");
string myObjectId = actualObject.Id // This should be what was passed in... "abc123"

I could give a code example to show how to change the id via a property but I've yet to see a case where you'd want an object identifier to change once it has been created. There would easily be other fields that you may want to change but that is a different question.

ono2012
  • 4,967
  • 2
  • 33
  • 42