How to set null value to int in c#? - c#

int value=0;
if (value == 0)
{
value = null;
}
How can I set value to null above?
Any help will be appreciated.

In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int>, or int? for short:
int? value = 0;
if (value == 0)
{
value = null;
}
Further Reading
Nullable Types (C# Programming Guide)

Additionally, you cannot use "null" as a value in a conditional assignment. e.g...
bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;
FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.
So, you have to cast the null as well... This works:
int? myint = (testvalue == true) ? 1234 : (int?)null;
UPDATE (Oct 2021):
As of C# 9.0 you can use "Target-Typed" conditional expresssions, and the example will now work as c# 9 can pre-determine the result type by evaluating the expression at compile-time.

You cannot set an int to null. Use a nullable int (int?) instead:
int? value = null;

int does not allow null, use-
int? value = 0
or use
Nullable<int> value

public static int? Timesaday { get; set; } = null;
OR
public static Nullable<int> Timesaday { get; set; }
or
public static int? Timesaday = null;
or
public static int? Timesaday
or just
public static int? Timesaday { get; set; }
static void Main(string[] args)
{
Console.WriteLine(Timesaday == null);
//you also can check using
Console.WriteLine(Timesaday.HasValue);
Console.ReadKey();
}
The null keyword is a literal that represents a null reference, one that does not refer to any object.
In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null
https://en.wikipedia.org/wiki/Null

Declare you integer variable as nullable
eg: int? variable=0; variable=null;

Related

why dont nullable strings have a hasValue() method?

I have a class which contains a nullable strings, I want to make a check to see whether they stay null or somebody has set them.
simliar to strings, the class contains integers which are nullable, where i can perform this check by doing an equality comparison
with the .HasValue() method - it seems like strings dont have this?
So how do check whether it goes from null to notNull?
public class Test
{
public string? a
public string? b
public int? c
}
var oldQ = new Test(c=123)
var newQ = new Test(c=546)
bool isStilValid = newQ.c.HasValue() == oldQ.c.HasValue() //(this is not possible?)&& newQ.b.HasValue() == oldQ.b.HasValue()
why is this not possible?
HasValue property belongs to Nullable<T> struct, where T is also restricted to be a value type only. So, HasValue is exist only for value types.
Nullable reference types are implemented using type annotations, you can't use the same approach with nullable value types. To check a reference type for nullability you could use comparison with null or IsNullOrEmpty method (for strings only). So, you can rewrite your code a little bit
var oldQ = new Test() { c = 123 };
var newQ = new Test() { c = 456 };
bool isStilValid = string.IsNullOrEmpty(newQ.b) == string.IsNullOrEmpty(oldQ.b);
Or just use a regular comparison with null
bool isStilValid = (newQ.b != null) == (oldQ.b != null);
Only struct in C# have HasValue method, but you can simple create your own string extension as below and that will solve your problem.
public static class StringExtension {
public static bool HasValue(this string value)
{
return !string.IsNullOrEmpty(value);
}
}
I hope this is helpful for someone.
The equivalent comparing to null would be:
bool isStillValid = (newQ.c != null) == (oldQ.c != null) && (newQ.b != null) == (oldQ.b != null);
That's the equivalent to your original code, but I'm not sure the original code is correct...
isStillValid will be true if ALL the items being tested for null are actually null. Is that really what you intended?
That is, if newQ.c is null and oldQ.c is null and newQ.b is null and oldQ.b is null then isStillValid will be true.
The Nullable<T> type requires a type T that is a non-nullable value type for example int or double.
string typed variables are already null, so the nullable string typed variable doesn't make sense.
You need to use string.IsNullOrEmpty or simply null

integer fields set as null

How to make an integer field accepts null values?
[Range(10, 65]
[Display(Name = "oh")]
public int oh { get; set; }
I'm currently using this code, but I'm getting not null on sql server (I haven't used [Required]).
Thanks a lot!
Use ? keyword
public int? oh { get; set; }
It makes the type a Nullable type. Now you can set null to oh
And then check for its value by:
if(oh.HasValue){
Console.WriteLine(oh.Value)
}
.HasValue says if it has value or null.
.Value gets you the actual value
use
int? for the data type.
I don't know how this will work in conjunction with Range...
You can use a nullable type:
int? intNullable = null;
With a nullable type, you have another features like a bool property called HasValue which return if the int has a value and Value to get a value without nullable.
if (intNullable.HasValue)
{
int value = intNullable.Value;
}
In your case
public int? oh { get; set; }
The difference it the int is a value type while int? is a reference type. The ? is just a shortcut to Nullable<T> class. Value types cannot be null, reference type can. Read more about here http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
You can use ? in cases where a value type might be null:
public int? oh { get; set; }

what does symbol '?' after type name mean

I am using Eto gui framework. I saw some magic grammar in their source code;
for example:
int x;
int? x;
void func(int param);
void func(int? param);
What's different? I am confused.
and the symbol ? is hard to google.
It means they are Nullable, they can hold null values.
if you have defined:
int x;
then you can't do:
x = null; // this will be an error.
but if you have defined x as:
int? x;
then you can do:
x = null;
Nullable<T> Structure
In C# and Visual Basic, you mark a value type as nullable by using
the ? notation after the value type. For example, int? in C# or
Integer? in Visual Basic declares an integer value type that can be
assigned null.
Personally I would use http://www.SymbolHound.com for searching with symbols, look at the result here
? is just syntactic sugar, its equivalent to:
int? x is same as Nullable<int> x
structs (like int, long, etc) cannot accept null by default. So, .NET provides a generic struct named Nullable<T> that the T type-param can be from any other structs.
public struct Nullable<T> where T : struct {}
It provides a bool HasValue property that indicates whether the current Nullable<T> object has a value; and a T Value property that gets the value of the current Nullable<T> value (if HasValue == true, otherwise it will throw an InvalidOperationException):
public struct Nullable<T> where T : struct {
public bool HasValue {
get { /* true if has a value, otherwise false */ }
}
public T Value {
get {
if(!HasValue)
throw new InvalidOperationException();
return /* returns the value */
}
}
}
And finally, in answer of your question, TypeName? is a shortcut of Nullable<TypeName>.
int? --> Nullable<int>
long? --> Nullable<long>
bool? --> Nullable<bool>
// and so on
and in usage:
int a = null; // exception. structs -value types- cannot be null
int? a = null; // no problem
For example, we have a Table class that generates HTML <table> tag in a method named Write. See:
public class Table {
private readonly int? _width;
public Table() {
_width = null;
// actually, we don't need to set _width to null
// but to learning purposes we did.
}
public Table(int width) {
_width = width;
}
public void Write(OurSampleHtmlWriter writer) {
writer.Write("<table");
// We have to check if our Nullable<T> variable has value, before using it:
if(_width.HasValue)
// if _width has value, we'll write it as a html attribute in table tag
writer.WriteFormat(" style=\"width: {0}px;\">");
else
// otherwise, we just close the table tag
writer.Write(">");
writer.Write("</table>");
}
}
Usage of the above class -just as an example- is something like these:
var output = new OurSampleHtmlWriter(); // this is NOT a real class, just an example
var table1 = new Table();
table1.Write(output);
var table2 = new Table(500);
table2.Write(output);
And we will have:
// output1: <table></table>
// output2: <table style="width: 500px;"></table>

C# Return value of a property which is nullable [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Type result with Ternary operator in C#
I ran into this scenario, and there doesn't seem to be a natural way to return a nullable int. The code below gives compilation error because the ternary operator doesn't like null.
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? rv : null;
}
}
So you (or just me) really have to go all the way and spell it all out:
public int? userId
{
get
{
int id;
if(int.TryParse(userIdString, out id)){
return id;
}
return null;
}
}
EDIT: Is there a more natural way of instantiating a nullable, to make the ternary operator work?
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? (int?)rv : null;
}
}
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? (int?)rv : null;
}
}
EDIT: I hadn't read the question carefully enough; the problem isn't that the conditional operator doesn't like nulls - it's that it needs to know what the overall type of the expression should be... and that type has to be the type of either the left-hand side, or the right-hand side. null itself is a type-less expression which can be converted to many types; int is a perfectly valid type, but it's one of the types which null can't be converted to. You can either make the right-hand side explicitly of type int? and get the implicit conversion of int to int? from the left-hand side, or you can perform a cast on the left-hand side, and get the implicit conversion of null to int?.
My answer is like James's, but casting the null instead:
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? rv : (int?) null;
}
}
This is to emphasize that it's not a null reference; it's a null value of type int?. At that point, the conversion of the int rv is obvious.
There are two other alternatives along the same lines to consider though:
return int.TryParse(userIdString, out rv) ? rv : new int?();
return int.TryParse(userIdString, out rv) ? rv : default(int?);
Personally I think the "casted null" is the nicest form, but you can make up your own mind.
Another alternative would be to have a generic static method:
public static class Null
{
public static T? For<T>() where T : struct
{
return default(T?);
}
}
and write:
return int.TryParse(userIdString, out rv) ? rv : Null.For<int>();
I don't think I really like that, but I offer it for your inspection :)
You're returning a (non-nullable) int or null in the same expression. You'll need to explicitly return a int? in your ternary expression for that to work.

c#: IsNullableType helper class?

Can anyone help?
I have some code that is shared between 2 projects. The code points to a model which basically is a collection of properties that comes from a db.
Problem being is that some properties use nullable types in 1 model and the other it doesn't
Really the dbs should use the same but they don't ..
so for example there is a property called IsAvailble which uses "bool" in one model and the other it uses bool? (nullable type)
so in my code i do the following
objContract.IsAvailble.Value ? "Yes" : "No" //notice the property .VALUE as its a bool? (nullable type)
but this line will fail on model that uses a standard "bool" (not nullable) as there is no property .VALUE on types that are NOT nullable
Is there some kind of helper class that i check if the property is a nullable type and i can return .Value .. otherwise i just return the property.
Anybody have a solution for this?
EDIT
This is what i have now..... i am checking HasValue in the nullable type version
public static class NullableExtensions
{
public static T GetValue(this T obj) where T : struct
{
return obj;
}
public static T GetValue(this Nullable obj) where T : struct
{
return obj.Value;
}
public static T GetValue<T>(this T obj, T defaultValue) where T : struct
{
return obj;
}
public static T GetValue<T>(this Nullable<T> obj, T defaultValue) where T : struct
{
if (obj.HasValue)
return obj.Value;
else
return defaultValue;
}
}
This is a little weird, but maybe you can use an extension method here:
static class NullableExtensions
{
public static T GetValue<T>(this T obj) where T : struct
{
return obj;
}
public static T GetValue<T>(this Nullable<T> obj) where T : struct
{
return obj.Value;
}
}
They will work with nullable or regular types:
int? i = 4;
int j = 5;
int a = i.GetValue();
int b = j.GetValue();
I wouldn't cast. use the ?? operator
http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx
bool? isAvailble = null;
//string displayIsAvailble = (bool)(isAvailble) ? "Yes" : "No"; //exception Nullable object must have a value.
string displayIsAvailble = (isAvailble ?? false) ? "Yes" : "No"; //outputs "no"
Console.WriteLine(displayIsAvailble);
(bool)(objContract.IsAvailble) ? "Yes" : "No"
Best I can suggest is to always cast to the nullable, then use the null coalescing operator to say what you want the value to be when it's null. e.g.:
string s3 = (bool?)b ?? false ? "yes" : "no";
The above will work whether b is defined as bool or bool?
Convert.ToBoolean(objContract.IsAvailble) ? "yes" : "no"
OR
Is this what you are looking for?
bool? n = false;
bool nn = true;
Console.WriteLine(n ?? nn);
One more alternative:
objContract.IsAvailble == true ? "Yes" : "No"
On the nullable, only true is true, null or false is false. On the regular bool, true/false is normal.
You could use:
bool? b1 = objContract.IsAvailable;
string s1 = b1.Value ? "Yes" : "No";`
This should work whether objectContract.IsAvailable is a bool or bool? or any other nullable type.
For dates for example:
DateTime? t1 = objContract.EitherNullableOrNotNullableDate;
string s1 = t1.Value.ToString();

Categories

Resources