Miamy
Miamy

Reputation: 2299

How to set array's member property via other one

Consider the next code:

    public Color TotalColor { get; set; }
    public string TotalColorName
    {
        get => TotalColor.ToString();
        set => TotalColor = Color.FromHex(value);
    }

It works good. Now I'm trying to implement the same approach for two arrays:

    public string[] AreaColorNames { set; } = new string[3];
    public Color[] AreaColors { get; } = new string[3];

How should I write the setter for AreaColorNames? It should be something like this:

AreaColorNames
{
    set
    { 
      AreaColors[index] = Color.FromHex(value);
    }
}

but we don't have an index parameter in setters. Is there some workaround? Thank you.

Edit

In my case a number of colors can be different, so I can't use approach "left-middle-right".

Let me explain what I'm trying to do. I'm developing an inhouse library for reading definite file format. Consumers will use it from different apps, e.g. desktop and mobile. So I don't want to read a color value itself, because in one system type Color is described in System.Drawing, in other - in Xamarin.Forms etc. I'm thinking I can have a ColorName property in interface which will be used as function parameter and appropriate setters in every implementation. Because library is dedicated for using in our own apps only, I couldn't bother about wrong using - it will be restricted by internal arrangements.

Upvotes: 0

Views: 50

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

There are a number of ways you could go about this. You could get really fancy using a custom collection type with indexers.

But I'd recommend finding the simplest approach based on what you actually need. For example, think about how AreaColorNames is used: does it really make sense for someone to set a specific index to a specific string? That sounds like you're inviting people to make mistakes. What if they provide an index higher than 2? What if they provide a string that doesn't represent a hex value?

If you know that you've only got three "Areas", is that an essential part of your model, which you can come up with a name for? For example:

public class AreaColors
{
  public Color LeftColor {get;set;}
  public Color MiddleColor {get;set;}
  public Color RightColor {get;set;}
  public IReadOnlyCollection<string> TotalColors => new[]{LeftColor, MiddleColor, RightColor}
}

I'd argue that coming up with a Color from a hex value should be done prior to setting it on an object like this: the writer of the consuming code should be forced to think about things like what they should do if the given string is not a valid color.

Upvotes: 3

Related Questions