Question mark '?' given in arguments of a method [duplicate] - c#

This question already has answers here:
What is the purpose of a question mark after a value type (for example: int? myVariable)?
(9 answers)
What does the question mark in member access mean in C#?
(2 answers)
Closed 6 years ago.
I have a code containing a class with the following method:
public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid){...}
My question is what does the question mark there do? My guess it has something to do with overloading since there's another overload method of AddEvent but I'm not sure...

Simple, this isn’t C++ code. It’s C#, where ? denotes a nullable value type. I.e. a value type that can also be null. int? is a shortcut for Nullable<int>.

Usually a simple type like int cannot be null, using ? allows the int to have a null value like an object.
Inside the function, you need to check to see if eventId is valid to use. You can do this by checking HasValue or equal to null. If you try to use it without checking, and it is null, then it will throw System.InvalidOperationException:
public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid)
{
// use HasValue
if (eventId.HasValue)
eventId++;
// or check for null
if (eventId != null)
eventId++;
}

Related

Unable to assign null to int? when using ternary (?:) operator [duplicate]

This question already has answers here:
Nullable types and the ternary operator: why is `? 10 : null` forbidden? [duplicate]
(9 answers)
Closed 3 years ago.
Can anyone help me understand why the following doesnt compile?
string intAsString = "123";
int? nullableInt = null;
nullableInt = !string.IsNullOrEmpty(intAsString)
? Convert.ToInt32(intAsString)
: null;
As it complains that:
Type of conditional expression cannot be determined because there is no implicit conversion between int and null
I expected that since int? can be assigned null, this statement should work fine. It's easy enough to work around, but I'd like to understand why my expectation was wrong.
You need to explicitly cast the Int32 you get from Convert.ToInt32:
string intAsString = "123";
int? nullableInt = null;
nullableInt = !string.IsNullOrEmpty(intAsString) ? (int?)(Convert.ToInt32(intAsString)) : null;
The compiler finds out you have "int", and "null" as your result type. It is not smart enough to find a type fitting both. Cast one or the other explicitly to int?

int? version available for String.IsNullOrWhiteSpace [duplicate]

This question already has answers here:
Nullable types: better way to check for null or zero in c#
(13 answers)
Closed 5 years ago.
Our application requires int? variables. I'm often checking both to make sure not null and not 0 and it does get lengthy.
Is there an out of the box version of String.IsNullOrWhiteSpace() or String.IsNullOrEmpty() for int?
Maybe this would require an extension method?
If there even was or when someone makes one, would something like this considered bad practice?
I don't think so but it's easy to write your own:
[Pure]
public static bool IsNullOrDefault<T>(this T? pValue)
where T : struct {
return pValue == null || pValue.Value.Equals(default(T));
// or as suggested in comments (tested)
return pValue == null || EqualityComparer<T?>.Default.Equals(pValue, default(T));
}

C# Convert.ChangeType can't convert int to System.Nullable [duplicate]

This question already has answers here:
convert int to nullable int?
(6 answers)
Closed 7 years ago.
Iam confused by the ChangeType Method of .Net. I wrote a extension method to convert object values (which come from database in my cases) in the expected type. So long iam not using nullable types this works pretty good.
Iam doing this so far:
public static T ConvertTo<T>(this object value)
{
T returnValue = default(T);
if ((value != null) &&
(value != DBNull.Value))
{
returnValue = (T)Convert.ChangeType(value, typeof(T));
}
return returnValue;
}
If i call:
int test = myObject.ConvertTo<int>();
Iam getting the int value or 0 if myObject doesn't contain a int.
Because it is possible to do the following:
int? test = 5;
I thought there is no problem to cast a int to int?. But if i call this:
int? test = myObject.ConvertTo<int?>();
Iam getting System.InvalidCastException. Invalid cast from System.Int32 to System.Nullable`1
The Exception is thrown in the Convert.ChangeType line.
Somebody knows why?
Because int? is shorthand for Nullable<int> which is different to int. Those are two different types in .Net. If you want to cast int? to int or vice versa you have to do it manually.
Edit
Conversion from double to int is defined whereas conversion from nullable types to normal numerical types is not.

C# code won't compile. No implicit conversion between null and int [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?
Why doesn't this work? Seems like valid code.
string cert = ddCovCert.SelectedValue;
int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
Display(x);
How should I code this? The method takes a Nullable. If the drop down has a string selected I need to parse that into an int otherwise I want to pass null to the method.
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
I've come across the same thing ... I usually just cast the null to (int?)
int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);

c# why can't a nullable int be assigned null as a value [duplicate]

This question already has answers here:
Conditional operator assignment with Nullable<value> types?
(6 answers)
Nullable types and the ternary operator: why is `? 10 : null` forbidden? [duplicate]
(9 answers)
Closed 9 years ago.
Explain why a nullable int can't be assigned the value of null e.g
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
What's wrong with that code?
The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
What Harry S says is exactly right, but
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
would also do the trick. (We Resharper users can always spot each other in crowds...)
Another option is to use
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
I like this one most.
Similarly I did for long:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;

Categories

Resources