C # If the value of an object is null, then why does it not give an error when it calls the extension method

Source: Internet
Author: User

If the value of an object is null, does it give an error when calling an extension method?

Person p = null;p. Extendmethod ();

The above code will not be an error, the beginning of this situation is very puzzled, asked Daniel. Daniel explains the following:

The extension function is only intended to make the code more readable, but it will eventually be translated into a standard static function call in the CLR.

Like what:

public static void Extmethod (This string str) {    if (!string. IsNullOrEmpty (str))    {         //For str processing          }    }

Call "string". Extmethod () will eventually be translated into Extmethod ("string"); So even if it's null, it won't be an error.

Null why can't I point out the extension function?


Obtain its own method by NULL as follows:

  

Try this ((string) null). Extmethod () must be able to point it out.

  

The key is to use the extension function to see the corresponding data type.

C # If the value of an object is null, then why does it not give an error when it calls the extension method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.