Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# "Boxing" into a property / 1-Arg Constructor By Assignment

Tags:

c#

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?

like image 492
Metal450 Avatar asked Feb 08 '23 18:02

Metal450


1 Answers

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.

like image 110
Yuval Itzchakov Avatar answered Feb 15 '23 12:02

Yuval Itzchakov