Property is a name of data fields which are use to
get and set the values. It is a member of class, Structs, and interfaces.
get{} : getter are use to return a value.
set{} : setter are use to get a value.
public int UserId { get; set; }
Example : get and set the
values, In this step 1, we create property in a class
using System;
using
System.Collections.Generic;
using System.Linq; using System.Text;
namespace
PropertyExample
{
public class UserDetails
{
public int UserId { get; set; }
public string UserName { get; set; }
public long PhoneNo { get; set; }
}
}
In this step 2, we set
the values which you want
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PropertyExample
{
public class SetValues
{
UserDetails _objUser=new UserDetails();
public UserDetails
SetVal()
{
_objUser.UserId = 001;
_objUser.UserName = "Anil";
_objUser.PhoneNo = 9090909090;
return _objUser;
}
}
}
In this step 3, we call
the property and get the values which you set the above class
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PropertyExample
{
class Program
{
static void Main(string[] args)
{
SetValues objSetVal = new SetValues();
UserDetails objUserDet = new UserDetails();
objUserDet=objSetVal.SetVal();
int id =
objUserDet.UserId;
string userName =
objUserDet.UserName;
long phone =
objUserDet.PhoneNo;
}
}
}
Property Explanation
- When we are using get modifier that is called a read-only property.
- When we are using set modifier that is called a write-only property.
- When we are using both get and set modifiers that is called a read-write property.
- Both get and set modifiers must be declared within the body of the property.
- We cannot assign values in read-only property.
- Properties are use to get and set the values using conditional statement.