While certainly not "official", you could use optional named parameters in the constructor or a separate factory/builder method:
public class MyClass
{
public string x { get; private set; }
public MyClass(Func<string> x = null)
{
if (x != null)
this.x = x();
}
}
with usage like:
var myClass = new MyClass(
x: () =>
{
//Do stuff..
if (2 + 2 == 5)
return "I like cookies";
else if (2 + 2 == 3)
return "I like muffins";
//More conditions...
else
return "I'm a bitter old man";
}
);
Console.WriteLine(myClass.x); //"I'm a bitter old man"
So, it's not the exact syntax you were asking for, but pretty close and skips the LINQ weirdness.
That said, I don't like it. Just offering it as food for thought. :)
EDIT: I figured I'd add a factory method style since it's plausible you're using this on a class that you can't (or don't want to) change its constructor:
public static class MyFactory
{
public static MyClass CreateMyClass(Func<string> x = null)
{
var myClass = new MyClass()
if (x != null)
myClass.x = x();
return myClass;
}
}
With similar usage (just calling a factory method instead):
var myClass = MyFactory.CreateMyClass(
x: () =>
{
//Do stuff..
if (2 + 2 == 5)
return "I like cookies";
else if (2 + 2 == 3)
return "I like muffins";
//More conditions...
else
return "I'm a bitter old man";
}
);
EDIT: And hey, while we're at it. Why not go off the deep end and do it with a separate builder and abuse implicit operators!
public class MyClassBuilder
{
public Func<string> x { get; set; }
public static implicit operator MyClass(MyClassBuilder builder)
{
var myClass = new MyClass();
if (builder.x != null)
myClass.x = builder.x();
return myClass;
}
}
With usage like:
MyClass myClass = new MyClassBuilder
{
x = () =>
{
//Do stuff..
if (2 + 2 == 5)
return "I like cookies";
else if (2 + 2 == 3)
return "I like muffins";
//More conditions...
else
return "I'm a bitter old man";
}
};
So now the syntax is identical, except you have to explicitly type your instance instead of using var.
what are some other ways to do the same thing?What are you trying to do? Where is the property?condition1 ? "cookies" : condition2 ? "muffins" : "bitter"