In C#, suppose you have a simple class like:
public class MyFloat
{
public float Value { get; set; }
public MyFloat()
{}
public MyFloat(float _Value)
{
Value = _Value;
}
}
Does such a syntax exist that would allow you to short-hand initialize its Value property as something like:
MyFloat[] Arg_f;
Arg_f = new MyFloat[] { 1, 2, 3 };
Rather than needing to explicitly call the constructor, like:
Arg_f = new MyFloat[] { new MyFloat(1), new MyFloat(2), new MyFloat(3) };
Or equivalently, i.e.
MyFloat myFloat = 5f; //Implicitly assign 5f to myFloat.Value
float myFloatValue = myFloat; //Implicitly get myFloat.Value
This is obviously similar to boxing/unboxing, except that I'm trying to "box" into a specific object property. Or you might say I'm trying to implicitly call the 1-arg constructor by assignment.
Is something like this possible in C#, or am I just on a wild goose chase?
This is possible via an implicit conversion:
public static implicit operator MyFloat(float f)
{
return new MyFloat(f);
}
Now this will work:
var myFloats = new MyFloat[] { 1, 2 };
This is obviously similar to boxing/unboxing, except that I'm trying to "box" into a specific object property.
This isn't about boxing, it is about the ability to convert one type to another, implicitly, as you don't want the explicit type declaration.
Personally, although possible, I don't like using implicit conversions. They cause ambiguity ("how is this converted to MyFloat
?") and may surprise developers when reading the codebase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With