Reputation: 39
I don't understand what the following lines mean, please explain them to me.
1.
DateTime? pInsertDate;
At this variable declaration, What does ?
mean?
2.
using (TransactionScope scope = new TransactionScope())
At this object creation, What does using
mean?
Upvotes: 1
Views: 449
Reputation: 169123
SomeType?
is syntactic sugar for Nullable<SomeType>
. It can only be applied to value types (not reference types) and indicates that the variable will also be able to store a value equivalent to what null
is for reference types. (Value types cannot be null, so the Nullable<T>
type was added to allow for such cases. It's extremely useful in database binding code, where nullable columns are common.)
using (SomeType x = y) { ... }
is syntactic sugar for:
SomeType x = y;
try {
...
} finally {
if (x != null)
((IDisposable)x).Dispose();
}
This pattern is common when using objects whose classes implement IDisposable, as a way to automatically clean up such objects when they are about to fall out of use.
Upvotes: 0
Reputation: 1501163
The ?
suffix is syntactic sugar for using Nullable<T>
. So your declaration is equivalent to:
Nullable<DateTime> pInsertDate;
See the MSDN documentation for nullable value types for more information. Basically a nullable value type value can represent any of the values of the non-nullable underlying type (DateTime
in this case) as well as the special "null" value. This isn't a null reference, but it's usually used with the same sort of connotations - "no value". For example, a Person class might have a DateTime DateOfBirth
property, but a DateTime? DateOfDeath
property, which would be null if the person was still alive.
A using
statement is a way of automatically calling Dispose
on the reference acquired in the first part of the statement at the end of the body. So your code is broadly equivalent to:
TransactionScope scope = new TransactionScope();
try
{
// Body of the using statement
}
finally
{
if (scope != null)
{
scope.Dispose();
}
}
In this case of course we know thatscope
won't be null because we're calling a constructor, but that's the general expansion. (You could have used a method call to obtain the transaction scope, for example - in which case it could have returned null, but the generated code won't throw a NullReferenceException
.)
Upvotes: 6