property read only for external world and writable in the same assembly?

14 0 0
                                        

Let’s us first try to understand this c# / .NET interview question and answers. 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 canrun the below code.

Customer obj = newCustomer();

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 = newCustomer();

obj.CustomerCode = “c001″;

This can be achieved by have different access modifiers for “SET” and “GET properties on the “CustomerCode” property. In case you are new to access modifiers , see c# interview questions :- What are the different access modifiers in c# ?.

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.

classCustomer

     {

privatestring _CustomerCode = “”;

publicstring CustomerCode

{

get { return _CustomerCode; }

internalset { _CustomerCode = value; }

}

This question is taken from the book written by Shivprasad koirala .NET interview questions by BPB publications.

You can see SQL Server interview questions and answersarticle which is hosted on code project.

property read only for external world and writable in the same assembly?Where stories live. Discover now