Home »
C# programming
Properties (get and set) in structure in C#
In this example, we are going to learn how to define set and get properties within a C# structure? Here, we have an example that have set and get properties within the structure.
Submitted by IncludeHelp, on January 16, 2018
In C#, we can define set and get properties in any structure and they can be accessed through object of that structure.
Generally, to set a value to private data member of a structure, we use public method with the arguments, but using set property we can directly assign value to that data member.
For example: there is a data member named roll_number, for this we create a set property named ‘Roll’, then by using object name we can directly assign value to the roll_number like: S1.Roll = 101; Where, S1 is the object of structure.
Same functionality with the get property, to define it we give a name of the properly and returns the value of private data member. Consider the given example.
Example:
using System;
using System.Collections;
namespace ConsoleApplication1
{
struct Student
{
private int roll_number;
private string name;
public int Roll
{
get
{
return roll_number;
}
set
{
roll_number = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class Program
{
static void Main()
{
Student S1 = new Student();
S1.Roll = 101;
S1.Name = "Shaurya Pratap Singh";
Console.WriteLine("Roll NO: " + S1.Roll + "\nName: " + S1.Name);
}
}
}
Output
Roll NO: 101
Name: Shaurya Pratap Singh