C #6.0 (C # vNext): Nameof Expressions

Source: Internet
Author: User

C #6.0 (C # vNext): Nameof Expressions
The Nameof Expressions parameter is the expression for obtaining the name.
First look at the example:

Previous writing:

void Foo(Bar bar){    if (bar == null)    {        throw new ArgumentNullException("bar");    }}

New statement:
void Foo(Bar bar){    if (bar == null)    {        throw new ArgumentNullException(nameof(bar));    }}

In this way, you do not need to write the "bar" string. When we rename the bar, the program can also properly reflect the correct name.

Nameof can be used to obtain: Class Name, method name, parameter name, Attribute name.
Example:

Public class MyClass {[TestMethod] public static void Show (int age) {Console. writeLine (nameof (MyClass); // output the MyClass class name Console. writeLine (nameof (Show); // output the Show method name Console. writeLine (nameof (age); // output ageConsole. writeLine (nameof (testmethodattrieline) // output Attribute name }}

Another practical situation is as follows:
class Bar : INotifyPropertyChanged{    private int foo;    public int Foo    {        get { return foo; }        set        {            foo = value;            PropertyChanged(this, new PropertyChangedEventArgs(nameof(Foo));        }    }    public event PropertyChangedEventHandler PropertyChanged;}

Use nameof (Foo) to replace the string "Foo ";

Related Article

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.