Why new while returning for overloaded operators for DBBool (TriState) implementation in C#

你。 提交于 2020-01-07 08:24:37

问题


If you look for the DBBool implementation in C#, few overloaded operators (logical operators |, &, !) new while returning. I believe that is not necessary and a small waste of memory. DBBool is a struct and a copy is made when it's passed into a method so there is no reason for that.

// Logical negation operator. Returns True if the operand is False, Null 
// if the operand is Null, or False if the operand is True. 
public static DBBool operator !(DBBool x)
{
    return new DBBool(-x.value);
}
// Logical AND operator. Returns False if either operand is False, 
// Null if either operand is Null, otherwise True. 
public static DBBool operator &(DBBool x, DBBool y)
{
    return new DBBool(x.value < y.value ? x.value : y.value);
}
// Logical OR operator. Returns True if either operand is True,  
// Null if either operand is Null, otherwise False. 
public static DBBool operator |(DBBool x, DBBool y)
{
    return new DBBool(x.value > y.value ? x.value : y.value);
}

It should be this way without newing.

public static DBBool operator !(DBBool x)
{
    if (x.value > 0) return False;
    if (x.value < 0) return True;
    return Null;
}
public static DBBool operator &(DBBool x, DBBool y)
{
    return x.value < y.value ? x : y;
}
public static DBBool operator |(DBBool x, DBBool y)
{
    return x.value > y.value ? x : y;
}

回答1:


  1. it is a struct, so "new" really means "initialize a value on the stack" - this is cheap and is not the same as a new object
  2. most structs are immutable; I'm guessing this is too; hence it can't just mutate the parameter value and return that - it must initialize a new value with the desired contents


来源:https://stackoverflow.com/questions/12082201/why-new-while-returning-for-overloaded-operators-for-dbbool-tristate-implement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!