I know it only allows the class to set it, but what is the point?
How do I solve the problem of having readonly ids?
Say I have a person class:
public class Person { public string Name { get; set; } public int Id { get; private set; } public int Age { get; set; } }
And this is in an Entities.dll
, used by a GUI, BL and DAL.
The GUI calls the BL:
List<Person> p = BL.PeopleBL.GetPeople();
For the sake of the example calls the DAL:
... while(dr.read()) { returnPersonList.add( new Person{ Age=dr.GetInt32(1), Id=dr.GetInt32(0), Name=dr.GetString(2)}) } ...
of course I cannot do that cause Id is a private set; What is the proper way to do this?
How can I let the BL/Dal set the Id, but not on the GUI?
Or is this not even the proper use of a private set?
I just wanted to add that this is your typical DB app, where the pk is the Id and should not be changed( only by the BL/DAL)
The public setter means that the value is editable by any object present outside the class. On the other hand, the private setter means that the property is read-only and can't be modified by others.
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.
Just because you can set a member before the constructor, does not mean that you should, for, with multiple constructors, this makes it HARD to follow the logic. Private setters force you to set values inside of constructor or later.
Using only private(set) means that the getter is internal - so not accessible outside the module.
This is one possible solution although not very clean:
internal
BAL.dll
& DAL.dll
Internal Visible in assemblyinfo.cs
public class Person { public Person(int id) { this.Id=id; } public string Name { get; set; } public int Id { get; internal set; } public int Age { get; set; } }
AssemblyInfo.cs
for Entities.dll
[assembly: InternalsVisibleTo("DAL"), InternalsVisibleTo("BAL")]
That way all your internals will be visible to DAL & BAL. This may not be desirable but I'm just suggesting one possible solution.
The two common approaches are either that the class should have a constructor for the DAL to use, or the DAL should use reflection to hydrate objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With