简体   繁体   中英

What would be the advantage for using the following statements?

Recently, I ran into the following lines:

StringBuilder sb = default(StringBuilder);
sb = new StringBuilder();

I would simply write the statement(s) like

StringBuilder sb = new StringBuilder();

What would be the advantage for using default(StringBuilder) statements?

Based on all the great feedback, I came up with a new question.

EDIT: Can you see an advantage or disadvantage to doing something like this? (it does compile)

var sb = default(StringBuilder);

Again like was mentioned I believe we are looking at whether there is a scope issue or not, but the biggest problem might be objects not getting initialized properly. what are your thoughts?

In general, nothing. There is no reason to initialize the variable, then set it in the next line of code. Your second statement is cleaner.

There are few reasons to split declaration and assignment. This typically is only required if there are scoping issues involved, such as trying to use exception handling around the assignment:

StringBuilder sb = null;

try
{
    // Using a statement that may throw
    sb = GetAStringBuilder();
}
catch
{
    //...
}

// The compiler will warn about a potentially 
// uninitalized variable here without the default assignment
if (sb != null)  
{
    //...

In this case, you need to split the two because your doing the assignment within a local scope (the try ).

If this isn't the case, then it's better to keep them together.

There is no advantage whatsoever; the second snippet is more concise and more readable.

The advantage of using default comes up only when you develop a generic class that works with parametrized types. Sometimes, it is not known whether the type is a reference type or a value type or a struct. The default keyword returns null for reference types and 0 for numeric value types.

For more details, please see http://msdn.microsoft.com/en-us/library/xwth0h0d%28v=vs.80%29.aspx

The default keyword is often used with the initialization of generic types, where one cannot be certain whether we are dealing with a value type (initialized eg to zero) or a reference type (initialized to null). As per other answers, in the example you provided, there is little purpose either initializing StringBuilder and reassigning it immediately, nor using the default keyword.

In .net 3.5 there is one additional convention which you may come across, viz:

var sb = new StringBuilder();

Here the type of sb is inferred from the RHS of the assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM