Interview Tips Interview Tips, Interview Questions and Answers

9Sep/100

Interview Questions: What are Properties in .NET, What are the advantages of using Properties in .NET, How to declare a property in .NET?

The primary building block of any .NET object is Data Members. Data members holds data for each objects and thus separates with other members.  Properties provide control access to the fields exposed from the class.
Each Properties in .NET is provided with two methods, Get / Set. Get is called whenever the user wants to access the value of the property, while Set is called whenever the value of the property is set.
It is always better to use properties to be exposed publicly from outside rather than public variable. This gives the programmer ability to validate the data before setting it to the member or determine what value to be sent before getting the value.  This makes properties in .NET very useful.
Say for instance


// Private variable for the property

private string m_CategoryName = string.Empty;

// Declare the property now

public string CategoryName

{
get { return m_CategoryName; } set { m_CategoryName = value; }
}   // Private variable for the property private MyClass mfield = null; // Declare the property now public MyClass MyProperty {
get {
this.mfield = this.mfield ?? new MyClass(); // Null coalesce return this.mfield;
} set {
if (value == null) { //throw exception } else this.mfield = value;
}
}

Here mfield is the mapped data element which is set from outside using MyProperty.

Another way of declaring a property

You can also declare properties in the following way.


public MyClass MyProperty { get;set; }

public string CategoryName { get;set; }

Here, you can see that we have declared properties without declaring private data member for them. This works in the same way as the first code snippet as internally, .NET declares a private member for this property.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.