Pergunta

I don't know:

  1. if this works.
  2. if it's a good idea.
  3. 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.

Foi útil?

Solução

I think the idea of having an OrNew method is fine. Especially if you're striving to make a fluent interface. However I would change 3 things about it

  1. Don't have a hidden flag that controls the behavior (ThrowIfNull). This makes it impossible for someone to read an OrNew call an understand what it does.
  2. Use a new constraint in favor of the less safe Activator.CreateInstance<T>() call
  3. I'd call it something other than DebugLogic. Generally (but not always) extension method containers end with the Extensions .

For example

public static class LogicExtensions {
  public static T OrNew<T>(this T obj) where T : class, new() {
    if (obj != null) {
      return obj;
    }
    return new T();
  }
}

Outras dicas

The name of this operation is clearly: DefaultIfNull

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top