I don’t know:
- if this works.
- if it’s a good idea.
- what it is called in order
to find out more about it.
But I think the intent is fairly apparent.
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
Intended usage:
var customer = order.Sale.OrNew().Customer.OrNew().Name
What am I doing? Is this insane or helpful? It seems helpful.
I think the idea of having an
OrNewmethod is fine. Especially if you’re striving to make a fluent interface. However I would change 3 things about itThrowIfNull). This makes it impossible for someone to read anOrNewcall an understand what it does.newconstraint in favor of the less safeActivator.CreateInstance<T>()callDebugLogic. Generally (but not always) extension method containers end with theExtensions.For example