In the previous article we saw how to implement a One-To-Many relationship a in C# class. You can find it here:
Implement one to many relationship in C# class.
In this article we will learn to implement a One-To-One relationship between two classes. As in the previous article, at first we will try to understand the best use of a One-To-One relationship.
There might be a situation where we need to implement a relationship between a student and his registration number. In a university a student has one registration number. Another example of a One-To-One relationship is a happy couple. Ha..Ha.. Ok, then implement an example of a happy couple relationship.
Happy couple relationship
This will show an example of a One-To-One relationship. Have a look at the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Client
{
class boy
{
Girl g = new Girl();
public string BoyName { get; set; }
public Girl getSetGirl
{
get { return g;}
set {g = value; }
}
public void Print()
{
Console.WriteLine("Boy Name:- " + this.BoyName);
Console.WriteLine("Girl Name:- " + this.getSetGirl.GirlName);
}
}
class Girl
{
public string GirlName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Girl a = new Girl();
a.GirlName = "Rimpa";
boy b = new boy();
b.BoyName = "Sourav";
b.getSetGirl = a;
b.Print();
Console.ReadLine();



Join the conversation! Your thoughts help the community grow.