I have some questions in C#
-
what are the differences between null comparisons null == value and value == null (value is a variable of any kind: int, string, float,…)
-
I heard that using prefix increment ++i instead of i++ in some case will enhance the program performance. Why is it so?
-
I have a snippet code as follow:
private int _number; public int Number { get { return _number} set { _number = value} } public double Test { get { if (null == Number) return 1.1; else return 2.2; } }
the question is why here we use null == Number but not null == _number or Number == null or _number == null
4. if I have a struct as follow:
public struct Vector
{
public double X;
public double Y;
public Vector(double x, double y)
{
X = x;
Y = y;
}
}
public class Test
{
public Vector Position;
public void StructLength(Test t2)
{
Vector v = this.Position - t2.Position;
if (v.Length > 10)
return false;
}
}
if we subtract 2 struct likes above, what will be return? and the Length properties of struct will return what?
Is anyone willing to enlighten me?
Thank in advance
In most cases it won’t make any difference. It shouldn’t make any difference. If someone overloads the == operator badly it might do. Personally I prefer
if (x == null).You should ask for specifics when you hear this sort of thing. In some cases it could make a difference (at least in the past, in C), but when it’s used as a statement on its own it’s entirely irrelevant – use whichever you find more readable. When used in a side-effecting way (e.g. as a method argument) there may be a tiny, tiny difference – but it’s never likely to be significant.
It makes no difference whether you use the property or the local variable in this case. In some other cases it may make a difference, depending on the code in the property. Comparing an
intwithnullis always going to give a result offalsethough, so 2.2 will always be returned.Your code at the moment won’t compile – you’d need to overload the
-operator inVectorfor it to work, at which point the behavior will depend on the code in the-operator. The same is true for the Length property.