Powered by Blogger.

Sunday, February 23, 2014

Properties in C#.Net

In this post we will discuss about properties in C#.Net. Properties of an object are the characteristics the object has.

Also check out:

- How to make scaling animation effect using AnimationExtender Control in Asp.Net?

- Show confirmation message in gridview for delete in Asp.net

- How to add Eval for hyperlink in gridview in asp.net?

Consider a Person object.The most common properties i.e the characteristics does a Person have are:

First name

Last name

Date of birth

You define a property in a class with the Property keyword (in VB.NET) or with a property header similar to a method in C#. In both languages, you use a Get block (get in C#) and a Set block (set in C#) to define the so-called getters and setters of the property. The getter is accessed when an object is asked for the value of a specific property, and the setter is used to assign a value to the property. You can also check generics here.

Properties only provide access to underlying data stored in the object; they don’t contain the actual data. To store the data, you need what is called a backing variable.consider the below example


Public Class Person
Private _firstName As String
Public Property FirstName() As String
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
End Class

public class Person

private string _firstName;
public string FirstName

get { return _firstName; }
set { _firstName = value; }



The FirstName property has a backing variable called _firstName, LastName has one called _lastName, and so on.

The main reason for a property in a class is to encapsulate data. The idea is that a property enables you to control the data that is being assigned to it.

For simple properties that don’t need any data manipulation or validation, you can use so-called automatic properties. Automatic properties used to be available in C# only, but starting with the release of .NET 4, automatic properties are now available in VB.NET as well.Consider the below syntaxs.

Public Property DateOfBirth As DateTime

public DateTime DateOfBirth { get; set; }

The Visual Basic implementation of automatic properties has one advantage over the C# version: you can declare the property and give it a value in one shot like below

Public Property myDate As DateTime = DateTime.Now