Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Dear All,

Please suggest some methods or example, to set Int = 0 to null and set the date also null if Int field is null or zero correspondingly in C#.
Posted
Comments
Bernhard Hiller 24-Jun-13 2:44am    
Do you actually talk about inserting those values into a database?

Integers cannot be null unless you declare them specifically as a "nullable type" by adding the '?' Suffix to the declaration:
C#
int? myNullableInt = null;
 
Share this answer
 
Comments
Ron Beyer 22-Jun-13 18:23pm    
Yup, +5, although it should be noted once you create a nullable value type, its basically not a full value type anymore. You can't assign int x = myNullableInt, since this will create a compile error. You also can't pass it to a function without explicitly casting it.
Member 10959895 14-Nov-14 6:54am    
h
OriginalGriff 14-Nov-14 7:08am    
And is that supposed to mean something?
If so, what?
Afzaal Ahmad Zeeshan 14-Nov-14 7:46am    
Maybe a laughter without the remaining "aha" ;P
OriginalGriff 14-Nov-14 7:50am    
Maybe he means "hello", but he's a really, really, slow typist?
Their are two ways to declare int as Nullable in c# .Net.

First one is
Nullable<int> i = null;

and the Second is
int? d = null;
 
Share this answer
 
You could also do something like:
C#
public class NullableIntExample
{
  private int i = 0;
  private DateTime dt = DateTime.Now;

  public int? I 
  {
    get
    { 
      if (this.i == 0)
      {   
        return null;
      }
      else
      {
         return this.i; 
      }
   }

  public DateTime? DT 
  {
    get
    { 
      if (this.i == 0)
      {   
        return null;
      }
      else
      {
         return this.dt; 
      }
   }

}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900