I am returning this SpannerParameterCollection here in C#. I want to check if the LastPurchaseDate is null (essentially no purchases yet) and if it is, return null value rather than the CommitTimestamp. How would I do this?
return new SpannerParameterCollection
{
new SpannerParameter(nameof(Person.Name), SpannerDbType.String),
new SpannerParameter(nameof(Person.LastPurchaseDate), SpannerDbType.Timestamp, SpannerParameter.CommitTimestamp)
}
I've tried if statements and the IsNull() function, but both give me errors.
Related
I'm using C# in Visual Studio and I have a table with an attribute set to allow nulls, I try to get a query excluding null values like so:
var playerQueryDel = (from p in DB.Jugadores
where p.goles != null
orderby p.goles
select new
{
tiros = p.tirosPorteria,
goles = p.goles,
nombre = p.nombreJugador
}
).ToList();
Where goles is an attribute of type int that accepts nulls and I know that there are some records in the database with null values in this attribute, the problem is that is returns "empty" values, for example trying this:
System.Diagnostics.Debug.WriteLine($"Testing: {playerQueryDel[0]}");
Prints this:
Testing:
I also try to print to know if it is emptry like so:
System.Diagnostics.Debug.WriteLine($"{playerQueryDel[0] == null}");
Prints false, what is the cause of this "not null but empty" value and is there a way to check without having to parse it to something else?
I'll upload more information if needed :)
A couple of things to try: Check that the list contains any items. Check the individual field in the result being returned.
System.Diagnostics.Debug.WriteLine($"Testing: {playerQueryDel.Count}");
System.Diagnostics.Debug.WriteLine($"Testing: {playerQueryDel[0].goles}");
I've jumped into such a thing in my code and I don't really know how to read this. Would be nice if somebody could help me with this :)
return Company?.Call?.SingleOrDefault(cf => cf.Name == Client?.CallID)
?? Company?.Call?.SingleOrDefault(cf => cf.IsDefault)
?? new CallData();
The ?. operator is called a Null-conditional operator and is a new feature from C# 6, and was announced in October 2014. https://msdn.microsoft.com/en-us/library/dn986595.aspx
The first part: Company?.Call?.SingleOrDefault can be seen as similar to this:
if (Company == null)
{
return null;
}
else if (Company.Call == null)
{
return null;
}
else
{
return Company.Call.SingleOrDefault(....
}
But then the original coder uses the ?? Null-coalesce operator, which has been a part of C# since at least 2007. It means that if whatever is left of the ?? is null, evaluate what is right of the ?? and return that instead.
So the code basically means:
If Company is null, return new CallData()
If Company.Call is null, return new CallData()
If the first call to Company.Call.SingleOrDefault returns a CallData instance (having a certain value for the Name property) , return that instance
If the first call returns null, but the second call returns a CallData instance (being the default one) , return that instance
If both calls to SingleOrDefault return null, return new CallData()
This piece of code has some issues.
First of all, it is unreadable and should be refactored into something that is easier to understand. New language features are nice, but only when used responsibly.
Second: If there are more than one CallData instances with the same Name, the SingleOrDefault will throw an exception, but there might be a unique index in the database the prevents this. The same goes for IsDefault property - if there are more than one records with IsDefault = true, the SingleOrDefault call will throw an exception.
Split it to 3 expressions first, separated by the ??:
Company?.Call?.SingleOrDefault(cf => cf.Name == Client?.CallID)
??
Company?.Call?.SingleOrDefault(cf=>cf.IsDefault)
??
new CallData();
The returned value of the entire expression would be the first expression that is returning a non-null value.
Within each segment, once any of the properties accessed using ?. is null, the entire expression will be evaluated to null.
See Null-conditional Operators
I have just installed ReSharper, and it has altered
if(dto != null)
{
return new test{
obj1 = "",
obj2 = "",
}
}
into
return dto?.Select(item => new test
{
return new test{
obj1 = "",
obj2 = "",
}
I have not seen before
dto?.Select
tried to google the meaning with no luck.. could someone please explain , or point me in the right direction to the deffination
I gather its simply checking for null?
Null propagation operator is newly introduced in C# 6. return dto?.Select... means, if dto is null then this statement will return null else will execute the remaining part.
Another example, just making it up, assume you have Employee object with Address property which inturn has Lane (string), Pincode etc.
So if you need to get the address lane value you could do:
var lane = employee?.Address?.Lane;
Which will return null if employee or address is null; otherwise returns lane value.
This could be combined in many ways and is really handy.
For eg,
int someIntegerValue = someObject?.SomeIntValue ?? 0;
Basically you could avoid many null checks with this feature.
The question-mark operator acts on nullable values and
x?<operation>
translates to
x.HasValue ? x.Value.<operation> : null
It's basically saying "do this if I'm not null; otherwise keep me as null".
Do you have a
return null
statement later in your original code? I am surprised ReSharper would assume a return null in its transformation.
I cam across this line while going through some not that old code and don't understand why anyone would ever do it:
return dbStudents.MethodToReturnAllStudents()?.Select(x => new dtoStudent(x));
MethodToReturnAllStudents returns an IEnumerable<SQLDomain.Student> (dtoStudent) is in a different namespace -- all the SQLDomain.Student has been mapped from an IDataRecord.
Why would there be a ? in the middle of this statement. Will the LINQ Select try to do anything if MethodToReturnAllStudents returns null?
Is this just terrible code all around?
Side note: Either way, I am refactoring it to follow some alternative standards and to be much more readable.
This is not "old code", since this is a C#6 feature, the Null Conditional Operator. When used, it checks if the immediately preceding value is null before allowing property/method usage on that instance. If it is null, it returns null.
In this scenario, you can translate this code to:
var students = dbStudents.MethodToReturnAllStudents();
if (students == null) return null;
return students.Select(x => new dtoStudent(x));
However, there is actually a larger potential issue with this code than the unfamiliar operator.
The general consensus is that IEnumerable<T> should never return null and, as such, should never need to be null checked. It should always return a sequence that is either hydrated or empty.
That said, if this were in fact List<T> (or a null IEnumerable, although less common), this could be a real scenario (although I would still advocate for never returning null but rather an empty list).
You will have to decide as a development team if the Null Conditional Operator is more succinct and readable. Personally, I'm a fan of it, just not in this context since it is indicative of a larger design smell.
It's not "terrible" code, but it's non-intuitive if you're not familiar with the syntax. I personally enjoy the less-verbose options. LINQ will stop if MethodToReturnAllStudents() returns null and just return that null. It's basically saying
var retVal = dbstudents.MethodToReturnAllStudents();
if(retVal == null) {
return retVal;
} else {
return retVal.Select(x => new dtoStudent(x));
}
Now as users have pointed out, it shouldn't return null as the caller is expecting an IEnumerable.
var retVal = dbstudents.MethodToReturnAllStudents();
if(retVal == null) {
return new List<student>();
} else {
return retVal.Select(x => new dtoStudent(x));
}
Using a null coalescing operator makes the code even more concise and still properly handles return types so it doesn't return null:
return dbStudents.MethodToReturnAllStudents()?.Select(x => new dtoStudent(x)) ?? new List<student>();
It is the Null Conditional Operator
MSDN Documentation
If dbStudents.MethodToReturnAllStudents() is null, it will return null instead of executing .Select(x => new dtoStudent(x)) which would result in a NullReferenceException.
I have a DataTable resultSet; - I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.
This is the code that isn't working as expected when the "fk_id" field is null:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
//never reaches here
}
Note: using an int index instead of the Columns.IndexOf() isn't the issue.
Also does the "{}" have some other name in C#?
To check a column for DBNull in a DataSet, you can use the IsNull method:
if (resultSet.Rows[0].IsNull("fk_id"))
Your comparison against null is probably failing because DataSets don't use null to represent a "database NULL" value - they use DBNull.Value. If you need your code to work the way you've presented it, try this:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == DBNull.Value)
try
{
if (DT.Rows[0][0] != null)
{
//your code
}
}
catch
{
MessageBox.Show("AUTHANICATION FAILED.");
}
Please use:
dataTable.Select("FieldName is NULL")
this will give you the DataRows with null values in FieldName column.