How To Use Properties In C# net???

Here I am going to explain how to implement the properties in c# net.

What is Property?

The property has the same capability as the method. It is simple to use. Mainly it is used to access the data members when public fields are restricted. So only property is used in c#. Fields in the c# are in private by default. To use a property first you need to create a class.

How to declare a fields i.e variables??

Syntax: datatype variable;

Example: int a;

By default access modifier for the fields are private. If you want you can make it as public.

How to declare the property??

Using property you can able to assign a value for the fields as fields are in private.

Syntax: public datatype variable_name
                {
                get
                       {
                               return field_name;
                          }
                   set
                             {
                                field_name=value;
                            }

Make sure that the datatype used in field_name and property name must be same because you are creating the property for that field only.

The property name can be any name but the first letter of the property name must be in Upper_Case. The property has 2 blocks which have get and set block. Get block is used to get the value of the field and return a value for the field. Set block is used to assign a value for the field name.value is the keyword in the set block.

Example:

int number;

public int Number

{

get

{

return number;

}

set

{

number=value;

}

}

How to create an object for the class??

Syntax: Class_Name Object_name=new Class_Name();
Example: MyClass mObj=new MyClass();

How to pass a value for the property??

Go to the Main program and create an object for the class in which you have fields and property.

Using that object assign a value for the property.

Syntax: Obj_name.Property_name=give value for the field;

Example:mObj.Number=50;

Hope, now you know how to use properties in c# and how to assign a value for the field when field names are in private.