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.
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.
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";
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";
.