Simple example of Property in C#
Hello friends, here we will learn properties in c#. Properties allow you to control the accessibility of a class variable, and way to access variables from the outside in c#.
Types of properties in C#
- Read/Write properties - set and get
- Read only properties - get only
- Write only properties - set only
- Auto implemented properties - public int Id {get;set;};
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private int roll;
private string name;
public int Roll
{
get
{
return roll;
}
set
{
roll = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
Console.WriteLine("Enter the roll no :");
t.Roll = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the name");
t.Name = Console.ReadLine();
Console.WriteLine("Your roll no is " + t.Roll);
Console.WriteLine("Your roll no is " + t.Name);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private int roll;
private string name;
public int Roll
{
get
{
return roll;
}
set
{
roll = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
Console.WriteLine("Enter the roll no :");
t.Roll = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the name");
t.Name = Console.ReadLine();
Console.WriteLine("Your roll no is " + t.Roll);
Console.WriteLine("Your roll no is " + t.Name);
}
}
}
0 comments:
Post a Comment
Do not enter spam link