I have a class with many Properties and public Setters. On each Setter I want to check if the value has changed and if so calling an EventHandler method. The code ended up looking too long, too repetitive and very programmer error prone because I can make small mistake on the multiple setter methods and mess up things.
I would like to ask if there is any way to make this code smaller and more reusable (in case I want to add new Properties for example):
using System;
public class CosmeticsModel
{
private string _skin;
public string Skin {
get => _skin;
set
{
if (value != _skin)
{
_skin = value;
OnCosmeticChanged("Skin", _skin);
}
}
}
private string _eyes;
public string Eyes {
get => _eyes;
set
{
if (value != _eyes)
{
_eyes = value;
OnCosmeticChanged("Eyes", _eyes);
}
}
}
private string _mouth;
public string Mouth {
get => _mouth;
set
{
if (value != _mouth)
{
_mouth = value;
OnCosmeticChanged("Mouth", _mouth);
}
}
}
private string _accessory;
public string Accessory {
get => _accessory;
set
{
if (value != _accessory)
{
_accessory = value;
OnCosmeticChanged("Accessory", _accessory);
}
}
}
private string _shoes;
public string Shoes {
get => _shoes;
set
{
if (value != _shoes)
{
_shoes = value;
OnCosmeticChanged("Shoes", _shoes);
}
}
}
private string _hat;
public string Hat {
get => _hat;
set
{
if (value != _hat)
{
_hat = value;
OnCosmeticChanged("Hat", _hat);
}
}
}
private string _oneHandedWeapon;
public string OneHandedWeapon {
get => _oneHandedWeapon;
set
{
if (value != _oneHandedWeapon)
{
_oneHandedWeapon = value;
OnCosmeticChanged("OneHandedWeapon", _oneHandedWeapon);
}
}
}
// [... rest of the Class]
}