Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "extend" the property "class"?

I'm new to C# (started last week) so be cool with me ;). I'd like to know if I can somehow write a custom property, let me explain:

I have some partial classes that I complete by adding properties, but the pattern of all the getters and setters are the same so I'd like to factorize this:

public partial class Travel
{
    public String TravelName
    {
        get
        {
            return LocaleHelper.GetRessource(Ressource1);
        }
        set
        {
            if (this.Ressource1 == null)
                Ressource1 = new Ressource() { DefaultValue = value };
            else
                Ressource1.DefaultValue = value;
        }
    }

    public String TravelDescription
    {
        get
        {
            return LocaleHelper.GetRessource(Ressource2);
        }
        set
        {
            if (this.Ressource2 == null)
                Ressource2 = new Ressource() { DefaultValue = value };
            else
                Ressource2.DefaultValue = value;
        }
    }
}

As you can see, the only thing that change is Ressource1/Ressource2. My goal is be able to write something like:

public partial class Travel
{
    public LocalizedString TravelName(Ressource1);

    public LocalizedString TravelDescription(Ressource2);
}

Anybody have an idea to make this, or another idea to make my code cleaner? Thank you,

Guillaume

like image 228
Guillaume86 Avatar asked Dec 30 '22 15:12

Guillaume86


1 Answers

There is no facility to do this inside C# or .NET itself, but if you are doing lots of these it may be worth investigating aspect orientated programming through postsharp. Basically it will allow you to define an attribute that causes extra code to be injected at compile time. The code you type be something like:

public partial class Travel
{
    [LocalizedProperty(source = "Ressource1")
    public string TravelName { get; set; }

    [LocalizedProperty(source = "Ressource2")
    public string TravelDescription{ get; set; }
}

And at compile time PostSharp will replace the property with a template you have defined in the new LocalizedPropertyAttribute class.

like image 190
Martin Harris Avatar answered Jan 05 '23 16:01

Martin Harris