Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties private set;

Tags:

c#

properties

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)


like image 906
Eric Avatar asked Mar 02 '10 19:03

Eric


People also ask

What does get private set mean?

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.

Can properties be private?

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.

What is the use of private set in C#?

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.

What does private set mean in Swift?

Using only private(set) means that the getter is internal - so not accessible outside the module.


2 Answers

This is one possible solution although not very clean:

  1. Make the property you need to expose to BAL & DAL internal
  2. Mark 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.

like image 53
BlitzKrieg Avatar answered Oct 06 '22 06:10

BlitzKrieg


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.

like image 45
Rex M Avatar answered Oct 06 '22 07:10

Rex M