Arnon Hadas Arnon Hadas - 3 months ago 24
C# Question

Pass a Struct to String.Format as args

Is it possible use a struct as arguments for a

string.Format
like this:

struct kid
{
public string name;
public int age;
};

kid.name = alice;
kid.age = 2;

Console.WriteLine(String.Format("Her name is {0} and she's {1} years old", kid));


instead of this:

Console.WriteLine(String.Format("Her name is {0} and she's {1} years old", kid.name ,kid.age));


Edit:

The string will be read at runtime from a configuration file

Answer

Since .Format has a signature of String.Format(string format, params object[] args) you can convert your struct into an object array.

struct Kid
{
    public string name;
    public int age;

    public object[] ToObjectArray()
    {
        return new object[] {
            name, age };
    }
    public static implicit operator object[](Kid kid)
    {
        return kid.ToObjectArray();
    }
};

class Program
{
    static void Main(string[] args)
    {
        Kid kid=new Kid() { name="alice", age=2 };

        Console.WriteLine("Her name is {0} and she's {1} years old", kid);
        // Same as
        // Console.WriteLine(string.Format("Her name is {0} and she's {1} years old", kid));
    }
}

You could also take advantage of covariance and implicitly convert a string[] into object[] with

    public string[] ToStringArray()
    {
        return new string[] {
            name, age.ToString() };
    }
    public static implicit operator object[](Kid kid)
    {
        return kid.ToStringArray();
    }

instead of ToObjectArray()