Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

please explain the use of "default()" in this code

Tags:

c#

smo

source http://technet.microsoft.com/en-us/library/ms162234%28SQL.100%29.aspx

code

//Connect to the local, default instance of SQL Server. 

  { 

     Server srv = default(Server);
     srv = new Server(); 
     //Create a linked server. 
     LinkedServer lsrv = default(LinkedServer); 
     lsrv = new LinkedServer(srv, "OLEDBSRV"); 
     //When the product name is SQL Server the remaining properties are 
     //not required to be set. 
     lsrv.ProductName = "SQL Server"; 
     lsrv.Create(); 

  } 

why to use default(Server),? -even if its like server asd = new asd(); it will still connect to the default instance!

why to use default(linkedserver) -whats the point? we still specify the srv and provider and product!

like image 685
user287745 Avatar asked Jul 28 '10 13:07

user287745


3 Answers

default(...) is the default value operator. It evaluates to null for reference types, or the "zero" value for value types.

There's absolutely no point to it here... the variable is assigned a different value immediately. Here's the equivalent, tidier code:

Server srv = new Server(); 
//Create a linked server. 
LinkedServer lsrv = new LinkedServer(srv, "OLEDBSRV"); 
//When the product name is SQL Server the remaining properties are 
//not required to be set. 
lsrv.ProductName = "SQL Server"; 
lsrv.Create(); 
like image 86
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet


The default keyword was added in .NET 2.0 to satisfy generics. It just represents the default (meaning uninitialized) value of whatever type is passed to it. For reference types, this is null; for value types, it's the "zero" value. There's really no reason to use this operator unless you're writing a generic function.

like image 23
Adam Robinson Avatar answered Nov 14 '22 22:11

Adam Robinson


In your example it's not doing anything. It could be removed and the first two lines could be combined.

Server srv = new Server();

Same thing with the linked server.

LinkedServer lsrv = new LinkedServer(srv, "OLEDBSRV");
like image 22
Jerod Houghtelling Avatar answered Nov 14 '22 23:11

Jerod Houghtelling