C# 2.0 : Nullable Types
Posted by
hungle
Labels:
Dot Net
Problem
// User Classpublic class UserBecause C# 1.1 does not support null value for DateTime so the example above will throw exception if reader["RegisteredDate"] equals null.
{
private int userID;
private DateTime registeredDate;
public User() {}
public int UserID
{
get { return userID; }
set { userID = value; }
}
public DateTime RegisteredDate
{
get { return registeredDate; }
set { registeredDate = value; }
}
}
// Create User from a DataReader
public virtual User CreateUserFromReader(IDataReader reader)
{
User item = new User();
item.UserID = (int)reader["UserID"];
// throw exception if reader["RegisteredDate"] equals null
item.RegisteredDate = (DateTime)reader["RegisteredDate"];
return item;
}
Solution
Old schoold soltution :
// Create User from a DataReader
public virtual User CreateUserFromReader(IDataReader reader)Now in C#2.0 we can resolve null problem by declaration RegisteredDate as nullable DateTime with ? symbol :
{
User item = new User();
item.UserID = (int)reader["UserID"];
if (!reader.IsDBNull(reader.GetOrdinal("RegisteredDate")))
{
item.RegisteredDate = (DateTime)reader["RegisteredDate"];
}
else
{
item.RegisteredDate = new DateTime(1900,1,1,0,0,0,0);
}
return item;
}
// User ClassNullable type
public class User
{
private int userID;
private DateTime? registeredDate;
public User() {}
public int UserID
{
get { return userID; }
set { userID = value; }
}
public DateTime? RegisteredDate
{
get { return registeredDate; }
set { registeredDate = value; }
}
}
// Create User from a DataReader
public virtual User CreateUserFromReader(IDataReader reader)
{
User item = new User();
item.UserID = (int)reader["UserID"];
item.RegisteredDate =
(reader.IsDBNull(reader.GetOrdinal("RegisteredDate"))) ?
null : (DateTime)reader["RegisteredDate"];
return item;
}
Nullable types are constructed using ? type modifier.
Example :
int? age;
string? name;
DateTime? birthday;
A nullable type has two public read-only properties: HasValue and Value. When HasValue is true, the Value property returns the contained value. When HasValue is false, an attempt to access the Value property throws an exception.
DateTime? registeredDay;Null colalescence
// throw exception if RegisteredDate is null
registeredDay = user.RegisteredDate;
if (user.HasValue)
{
registeredDay = user.RegisteredDate
}
else
{
registeredDay = null;
}
C# 2.0 introduces a new operator called the null coalescing operator denoted by
double question marks ?? . If the instance is null, the value on the right is returned
otherwise the nullable instance value is returned.
int x = 10;
int? y = null;
int z = y ?? x;
response.write(z); // z = 10
y = 99;
int k = y ?? x;
response.write(k); // k = 99
blog comments powered by Disqus
Subscribe to:
Post Comments (Atom)