2

I would like to do something like this in C#:

Foo test = "string";

And now the object should be initialized. How can I achieve that? I can't get it to work but I know it is possible.

user247702
  • 23,641
  • 15
  • 110
  • 157
user3572544
  • 189
  • 7
  • Answer is here: [Overloading assignment operator in C#](http://stackoverflow.com/a/4537848/754376) – Vakho May 21 '14 at 16:56

2 Answers2

8

You're looking for an implicit conversion operator.

public class Foo
{
    public string Bar { get; set; }

    public static implicit operator Foo(string s)
    {
        return new Foo() { Bar = s };
    }
}

Then you can do:

Foo f = "asdf";
Console.WriteLine(f.Bar); // yields => "asdf";
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
0

You can use cast operator to implicitly:

sealed class Foo
{
    public string Str
    {
        get;
        private set;
    }

    Foo()
    {
    }

    public static implicit operator Foo(string str)
    {
        return new Foo
        {
            Str = str
        };
    }
}

Then you can do Foo test = "string";.

user247702
  • 23,641
  • 15
  • 110
  • 157