What is internal set property in c#?

前端 未结 8 558
悲&欢浪女
悲&欢浪女 2021-02-01 01:01

I just came across an unknown concept of c# for me. Can anyone tell me what the purpose of an internal set property is? What is its use? I know internal keyword is used for work

相关标签:
8条回答
  • 2021-02-01 01:13

    It means that the property can only be set by code that resides within the same assembly as the class delcaring the property.

    0 讨论(0)
  • 2021-02-01 01:21

    given a property declared public string MyString {get; internal set;} this means that

    • you can read the property's value from anywhere withhin your application (public string MyString)
    • but you may only write a new value to the property from inside the assembly in which it is declared - or from friend assemblies. (internal set;)
    0 讨论(0)
  • 2021-02-01 01:21

    it is mostly used with constructors like

    public class CustomerConfig
    {
         public string CustomerName { get; internal set; }
         public CustomerConfig(string customerName)
         {
            this.CustomerName = customerName;
         }
    }
    

    By this way, you can preset some parameters and make them readonly for other assemblies in your code.

    0 讨论(0)
  • 2021-02-01 01:22

    If you have a property with an internal set accessor (and public get accessor) it means that code within the assembly can read (get) and write (set) the property, but other code can only read it.

    You can derive the above information by reading about the internal access modifier, the public access modifier and properties.

    Also, you can read about Restricting Accessor Accessibility.

    0 讨论(0)
  • 2021-02-01 01:38

    Suppose you're designing an API for use by other programmers. Within this API, you have an object Foo which has a property Bar. You don't want the other programmers setting the value of Bar when they reference your assembly, but you have a need to set the value yourself from within your API. Simply declare the property as such:

    public class Foo
    {
       public string Bar { get; internal set; }
    }
    
    0 讨论(0)
  • Properties in C# 2.0

    In C# 2.0 you can set the accessibility of get and set.

    The code below shows how to create a private variable with an internal set and public get. The Hour property can now only be set from code in the same module (dll), but can be accessed by all code that uses the module (dll) that contains the class.

    // private member variables
    private int hour;
    
    // create a property
    public int Hour
    {
      get { return hour; }
      internal set { hour = value; }
    }
    
    0 讨论(0)
提交回复
热议问题