Powered by Blogger.

Saturday, March 8, 2014

Add property to class in C#.Net




In this post we will discuss how we can add properties to a class.

Also you can check out:

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

- Working with enterprise library for data access in asp.net Part-3

- Get nth highest lowest salary in SQL Server 2008

We can add properties by using Get and Set accessor. The get accessor allows your code to retrieve data from the object. The set accessor allows your code to set the object’s data.

Below is a class example that contains the properties:

public class Employee
{
private string name;
private int age;
private decimal salary;

public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

public int Age
{
get
{
return age;
}
set
{
age = value;
}
}

public decimal Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}

- Similarly you can create read only properties, which can be read but not set.

Example:
public decimal Salary
{
get
{
return salary;
}
}

Now we can use the properties like below:

Employee objEmployee = new Employee();
objEmployee.Name = "AspDotNetHelp.com";
objEmployee.Age = 1;
objEmployee.Salary =10000;

Automatic Properties:
Automatic properties are properties without any code. When you use an automatic property, you declare it, but you don’t supply the code for the get and set accessors, and you don’t declare the matching private variable.

Instead, the C# compiler adds these details for you.

Example:
public string Name
{
 get;
 set;
 }



0 comments

Post a Comment