Null behaviour as in t-sql [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# if-null-then-null expression
What I miss in C# is the treatment of null references like in sql server:
var a = SomeObject.Property1.Property2.Property3.Property4
If any of properties is null then I get NullReferenceException. Sometimes it would be more convenient if a would be set to null with no error and I could simply check for this.
Similarly,
var a = SomeList.FirstOrDefault(...).Select(...)
this would also throw exception if sequence would contain no elements rather then setting a to null.
So my question: is there short and nice way (using extensions maybe?) to implement sql-like behaviour in these scenarios?

This would only work with static properties, since an uninstantiated object is null. There would be no way doing this with extension methods either, as they take as their first parameter an instance of the object they are extending.
An ugly way of doing this ...
var a;
try {
a = SomeObject.Property1.Property2.Property3.Property4;
} catch (NullReferenceException) { }

Related

Why does is type / is var yield different results for null? [duplicate]

This question already has answers here:
What's the benefit of var patterns in C#7?
(4 answers)
Usage of Var Pattern in C# 7
(2 answers)
Closed 3 years ago.
Theoretical question: If you use the construct
if (someVar is object o) {
and you put in null for someVar, the result will be false. On the other hand, if you use
if (someVar is var o) {
the result will be true. Why is that so?
Complete code for testing:
object obj = null;
if (obj is object o) {
"object".Dump();
o.Dump();
}
if (obj is var o2)
{
"var".Dump();
o2.Dump();
}
Result in LinqPad:
var
null
Simple answer: because is object is specified as containing an implicit null-check, but is var is specified as not.
The best doc I can find is here (although that relates specifically to switch statements, and not if statements):
The introduction of var as one of the match expressions introduces new rules to the pattern match.
The first rule is that the var declaration follows the normal type inference rules: The type is inferred to be the static type of the switch expression. From that rule, the type always matches.
The second rule is that a var declaration doesn't have the null check that other type pattern expressions include. That means the variable may be null, and a null check is necessary in that case.
I can't say I understand the reason behind this (IMO) slightly odd decision...
As pointed out by #Camilo in the comments, this article contains some more details. This question thread also goes into a lot of detail.

How to invoke a property's method by property's name [duplicate]

This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 8 years ago.
I'd like to call a property's method of an object through reflection. For instance,
var query = DataContext().SomeTable.Where(u => u.UserID.contains("P");
I've tried the following but no luck:
var query = DataContext().SomeTable.Where(u => u.GetType().GetProperty("UserID").Name.contains("P");
Which returns null. Please help.
You want GetValue, not Name
((string)u.GetType().GetProperty("UserID").GetValue(u) ?? "").Contains("P")
The use of the ?? operator here is just a safeguard to make sure that Contains doesn't throw an exception if UserID is null.
You have to get the value of u, then use ToString on it:
u.GetType().GetProperty("UserID").GetValue(u, null).ToString().Contains("P");
Of course it have be a little bit improved: check if GetValue do not return null etc.
Note: Remember that you can somewhere cache PropertyInfo obtained from u.GetType().GetProperty("UserID") so you won't have to call it every time.

Using an "is" check when with an explicit cast [duplicate]

This question already has answers here:
Casting vs using the 'as' keyword in the CLR
(18 answers)
Closed 9 years ago.
How does the "is" operator work in C#?
I have been told that this :
if (x is string)
{
string y = x as string;
//Do something
}
is not as good as this:
string y = x as string;
if (y != null)
{
//Do something
}
Which is better and why?
FxCop issues Warning CA1800 in the first scenario (and not only when using as, but also when using an unchecked cast) as both is and the actual casts require certain type checking operations to determine whether the cast is successful or whether to throw an InvalidCastException.
You might save a few operations by just using as once and then checking the result for null if you are going to use the cast value anyway, rather than checking explicitly with is and then casting anew.
I think second is better cause in first case it will cast object 2 times, first time with is operator and second time in as operator.
while in second case it cast only one time.
The is operator checks if an object can be cast to a specific type or not
like
if (someObj is StringBuilder)
{
StringBuilder ss = someObj as StringBuilder
....
}
The as operator cast an object to a specific type, and returns null if it fails.
like
StringBuilder b = someObj as StringBuilder;
if (b != null) ...
I would use the first approach when more than one type is expected to be stored in x. (You might be passed a string, or a StringBuilder etc). This would allow for non-exception based handling.
If you are always expecting x to hold a certain type of value, then I would use the second option. The check for null is inexpensive and provides a level of validation.
-- Edit --
Wow. After reading some of the comments below, I started looking for more updated information. There is a LOT more to consider, when using as vs is vs (casting). Here are two interesting reads I found.
Does it make sense to use "as" instead of a cast even if there is no null check? and http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx?PageIndex=1#comments
Both of which seem to be well summarized by Jon Skeet's blog. http://www.yoda.arachsys.com/csharp/faq/#cast.as

null == object vs object == null [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is wrong in comparing a null with an object rather than an object with a null
I see some developers using the following null object checking in C#:
if (null == myObject)
{
}
rather than:
if (myObject == null)
{
}
I prefer the second statement, since it reads naturally (for me) from left to right.
Is there any reason for why the first one would be used? Are there any performance benefits, or is it purely taste?
Some people (Mostly C developers) prefer the first way because if you forget one = sign the code wont compile in C.
For example, when i forget one =;
int a = 0;
if(a=1) //Accidental assignment, luckily the C# compiler warns us for this. The C compiler wouldnt.
{
}
if(1=a) // This is not logical, and not valid in either C# or C.
{
}
However as Jamietre pointed out that unlike C its invalid in C# to implicitly cast an int to a boolean. The compiler still produces an error. It will however work when you compare booleans as such: if(a == true). However that in itself is rather odd, as you can (and should in my opinion) omit the == true.
Purely taste. They both will return exactly the same thing.
Pure taste, same as with comas, brackets etc.

Why use First instead of FirstOrDefault in LINQ? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use .First and when to use .FirstOrDefault with LINQ?
What is the point of using the First operator in LINQ, when you could use the FirstOrDefault operator instead?
var q = results.First(); // Error if empty
To respond directly to your specific question (why use First if you can always use FirstOrDefault), there are instances where you cannot use FirstOrDefault, because it loses information! The "default value" is likely a valid element type in the source list. You have no way to distinguish between the first element in the enumeration being null/default vs. there being no elements in the list unless you use First or first check if there are Any elements, which requires double-enumeration.
This is especially true for value-typed enumerables, such as int[]. default(int) is 0, which is also most likely a valid value of the array.
In general, the two methods represent different logical flows. First would be used if not having any elements is "exceptional" (an error), which then want to handle out-of-band in your application. In this scenario, you "expect" to have at least one element. FirstOrDefault returns null on an empty set, which means you need to do additional processing with the returned value. This is similar logic to the Parse vs TryParse methods on int/double/etc. In fact, your question in some ways leads itself to the more general question of why to ever use exceptions.
Since First throws an exception, it lends itself to all of the code-reuse opportunities that exceptions provide. For example, you could do:
try
{
x = arr1.First();
y = arr2.First();
z = arr3.First();
}
catch
{
throw new ArgumentException();
}
To explicitly force an exception to get raised versus performing a null check.
It's the same discussion as Int32.Parse vs. Int32.TryParse. The former throws an exception in case of failure, the latter returns false and the program continues smoothly...

Categories

Resources