If I have a user-defined type like this, there is some noise when using the type, as you have to add the propertyname Value when assigning or reading the content
public class CharArray
{
private byte[] _value;
public CharArray(int length)
{
_value = new byte[length];
}
public string Value
{
get => Encoding.ASCII.GetString(_value);
set
{
if (value.Length > _value.Length)
throw new Exception($"Max length is {_value.Length} characters");
_value = Encoding.ASCII.GetBytes(value.PadRight(_value.Length));
}
}
}
So usage will be something like this:
CharArray field = new CharArray(10);
field.Value = "Test";
string fieldAsString = field.Value;
Getting rid the Value property when reading the value is pretty easy, by just adding an implicit operator. This will enable users of CharArray to avoid ".Value" when reading the value
public static implicit operator string(CharArray c)
{
return c.Value;
}
However I have not found a way to avoid the .Value property when assigning a value. Any ideas?
I cannot use a static method, as I need the value given in the constructor. So I guess I am looking for a way to overload the = operator in a non static method. Is that possible in C# ?
You can make implicit conversion in other direction string
-> CharArray
:
public static implicit operator CharArray(string s)
{
return new CharArray(s.Length){ Value = s };
}
Then this works:
CharArray field = new CharArray(10);
field = "Test"; // all good!
string fieldAsString = field;