Home > Blockchain >  what to use with Dns.GetHostAddresses with First() or FirstOrDefault()
what to use with Dns.GetHostAddresses with First() or FirstOrDefault()

Time:12-11

  • Which one is better in this case First() or FirstOrDefault() ?

  • What will be the result of default if no IP address is found ? will it be null ?

    Dns.GetHostAddresses(hosturl).First().ToString()
    

or

Dns.GetHostAddresses(hosturl).FirstOrDefault().ToString()

CodePudding user response:

The difference between First() and FirstOrDefault() is only relevant in the case where the collection does not contain any elements.

In that case First() throws an exception, whereas FirstOrDefault() returns default(T) (which is null for a reference type). In your case, the first instruction

Dns.GetHostAddresses(hosturl).First().ToString()

will therefore throw an exception when the list is empty, while the second instruction

Dns.GetHostAddresses(hosturl).FirstOrDefault().ToString()

will also throw an exception (a NullReferenceException) if the list is empty, because ToString() is called on a null reference.

  • Related