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
It means that the property can only be set by code that resides within the same assembly as the class delcaring the property.
given a property declared public string MyString {get; internal set;}
this means that
public string MyString
)internal set;
)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.
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.
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; }
}
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; }
}