Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "default" in C# TcpClient clientSocket = default(TcpClient);

I found some code on how to write a TCP/IP client-server app in C# The server Main starts with this:

TcpListener serverSocket = new TcpListener(8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();

Unfortunately I have no idea as to what the keyword default is doing in the third line. I would have thought that the last line initialises clientSocket, so there would be no need to initialise it before.

like image 452
user1741137 Avatar asked Jan 19 '26 16:01

user1741137


1 Answers

default keyword is just setting the object clientSocket to null or default value of a reference type, since TcpClient is a class, (a reference type). It is same as :

TcpClient clientSocket = null;

In short it returns the default value of any type specified. For example, in case of int it will return 0. like:

int i = default(int); // i = 0

default is useful in generic code, where the type is unknown.

See: default Keyword in Generic Code (C# Programming Guide)

like image 167
Habib Avatar answered Jan 21 '26 06:01

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!