A recent question here made use of the default keyword in non-generic code that interests me:
StreamReader r = default(StreamReader);
What is the purpose served here? How is this different from:
StreamReader r;
Both statements define r. In ‘SLaks’ answer below, he clarifies that the use of default additionally sets r to null, but that could be done explicitly by just using null. Is this a style issue, or is there some utility served?
I have used default in generic code (and, of course, in switch statement blocks) but do not understand it’s purpose in this usage.
It’s different from
StreamReader r;in that it assigns the variable.It’s (completely) identical to
StreamReader r = null;.For reference types,
default(T)compiles tonull.For value types,
default(T)compiles tonew T().C#’s
default(T)keyword is actually equivalent to VB.Net’sNothingkeyword.