.NET interview questions: - How can you define a property read only for external world and writable in the same assembly?
Let’s us first try to understand this question. Let’s say if you have a class
called as “Customer” with a property “CustomerCode”.Now you want that anyone can
read from the “CustomerCode” property but this property can only be set from
within the assembly.
In other words any one can run the below code.
Customer obj = new Customer();
string x = obj.CustomerCode;
But setting of the value can be only done from within assembly. The below
code will run only if it’s within assembly and it will throw error if it’s
external to the assembly.
Customer obj = new Customer();
obj.CustomerCode =
"c001";
This can be achieved by have different access modifiers for “SET” and “GET
properties on the “CustomerCode” property.
So for the “GET” we will have public access modifiers and for “SET” we will
apply internal access modifiers. Now because “GET” is public this property can
be read anywhere and because the “SET” is internal it can only be accessed from
within assembly. Below goes the code for the same.
class Customer
{
private string _CustomerCode =
"";
public string CustomerCode
{
get { return _CustomerCode; }
internal set { _CustomerCode =
value; }
}
}
See the following .NET and
C# interview questions with answers video on IL code, CLR, CTS, CAS on UML:
-
http://
http://www.questpond.com/
Contributed by:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site http://www.questpond.com for
.NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Resourse address on xpode.com
http://www.xpode.com/Print.aspx?Articleid=698
Click here to go on website
|