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();
}
}
}
Here is the sample output.
Student and mark sheet relationship
It is also an example of a One-To-One relationship. Generally one student has one mark (answer) sheet in one examination. Have a look at the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Client
{
class Student
{
public string Name { get; set; }
public Marksheet GetSetMarksheet { get; set; }
public void Print()
{
Console.WriteLine("Name :- " + this.Name);
Console.WriteLine("Roll :- " + this.GetSetMarksheet.Roll);
Console.WriteLine("Total Mark:- " + this.GetSetMarksheet.TotalMark);
Console.WriteLine("Position :- " + this.GetSetMarksheet.Position);
}
}
class Marksheet
{
public int Roll { get; set; }
public int TotalMark { get; set; }
public int Position { get; set; }
}
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Name = "Sourav";
Marksheet m = new Marksheet();
m.Roll = 100;
m.TotalMark = 500;
m.Position = 10;
s.GetSetMarksheet = m;
s.Print();
Console.ReadLine();
}
}
}
Here is sample output.
Conclusion
In this article we learned to implement a One-To-One relationship between C# classes. Hope you have understood the concept. In a future article we will see how to implement a Many-To-One and Many-To-Many relationship between C# classes.