Nameof c что это

от admin

Name already in use

docs / docs / csharp / language-reference / operators / nameof.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

nameof expression (C# reference)

A nameof expression produces the name of a variable, type, or member as the string constant. A nameof expression is evaluated at compile time and has no effect at run time. When the operand is a type or a namespace, the produced name isn’t fully qualified. The following example shows the use of a nameof expression:

When the operand is a verbatim identifier, the @ character isn’t the part of a name, as the following example shows:

You can use a nameof expression to make the argument-checking code more maintainable:

Beginning with C# 11, you can use a nameof expression with a method parameter inside an attribute on a method or its parameter. The following code shows how to do that for an attribute on a method, a local function, and the parameter of a lambda expression:

. code language=»csharp» source=»snippets/shared/NameOfOperator.cs» .

A nameof expression with a parameter is useful when you use the nullable analysis attributes or the CallerArgumentExpression attribute.

C# language specification

For more information, see the Nameof expressions section of the C# language specification, and the C# 11 — Extended nameof scope feature specification.

Что нового в C# 6.0?

Microsoft выпустила предварительную версию Visual studio 2015 и .Net 4.6 для разработчиков. В новом C# 6.0 несколько новых возможностей, которые могут облегчить кодинг.

В этой статье рассмотрены новые возможности языка C# 6.0. Скачать новую VS можно по ссылке:
Microsoft Visual Studio Ultimate 2015 Preview

Инициализация свойств со значениями

В C# 6.0 мы можем инициализировать свойства со значениями, написав справа от них их значение. Это поможет избежать ошибки с null и пустыми значениями свойства.

Раньше:
Теперь:

Интерполяция строк

Каждый день нам приходится сталкиваться с конкатенацией строк. Кто-то в основном использует оператор “+”, кто-то — метод string.Format(). Мне лично по душе string.Format(). Но проблемы с ним всем известны: при слишком большом количестве параметров тяжело понимать, что означают каждое число – <1>, <2>, <3>. В C# 6.0 придумали новую возможность, которая должна объединить достоинства обоих методов.

Раньше:
Теперь:

По просьбе трудящихся IL код

Так же можно использовать условия:

Использование лямбда-выражений

В C# 6.0 свойства и методы можно определять через лямбда-выражения. Это сильно уменьшает количество кода.

Раньше:
Теперь:

Импорт статических классов

Все статические члены класса могут быть определены с помощью другого статического класса. Но нам приходится постоянно повторять имя данного статического класса. При большом количестве свойств приходится много раз повторять одно и то же.
В C# 6.0 появилась возможность импортировать с помощью ключевого слова using статические классы. Рассмотрим все на примере использования библиотеки Math:

Раньше
Теперь:

Это можно использовать не только внутри класса, но и при выполнении метода:

Раньше:
Теперь:

Null-условный оператор

C# 6.0 вводит новый так называемый Null-условный оператор (?.), который будет работать поверх условного оператора (?:). Он призван облегчить проверку на NULL значения.
Он возвращает null значения, если объект класса, к которому применен оператор, равен null:

Раньше:
Теперь:

nameof оператор

В C# 6.0 оператор nameof будет использоваться, чтобы избежать появления в коде строковых литералов свойств. Этот оператор возвращает строковый литерал передаваемого в него элемента. В качестве параметра можно передать любой член класса или сам класс.

Await в catch и finally блоках

До C# 6.0 нельзя было использовать в блоках catch и final оператор await. Сейчас такая возможность появилась. Ее можно будет использовать для освобождения ресурсов или для ведения логов ошибок.

Фильтры исключений

Фильтры исключений были в CLR, и они доступны в VB, но их не было в C#. Теперь данная возможность появилась, и можно накладывать дополнительный фильтр на исключения:

Инициализация Dictionary

В C# 6.0 добавлена возможность инициализации Dictionary по ключу значения. Это должно упростить инициализацию словарей.
Например, для JSON объектов:

В C# 6.0 много синтаксических изменений и новых возможностей. Также Microsoft улучшает новый компилятор в плане производительности.

What is the purpose of nameof?

Version 6.0 got a new feature of nameof , but I can’t understand the purpose of it, as it just takes the variable name and changes it to a string on compilation.

I thought it might have some purpose when using <T> but when I try to nameof(T) it just prints me a T instead of the used type.

Any idea on the purpose?

Patrick Hofman's user avatar

17 Answers 17

What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged event. There are numerous cases where you would want to have the name of the property.

Take this example:

In the first case, renaming SomeProperty will cause a compilation error if you don’t change both the property definition and the nameof(SomeProperty) expression. In the second case, renaming SomeOtherProperty or altering the "SomeOtherProperty" string will result in silently broken runtime behavior, with no error or warning at build time.

This is a very useful way to keep your code compiling and bug free (sort-of).

(A very nice article from Eric Lippert why infoof didn’t make it, while nameof did)

Patrick Hofman's user avatar

It’s really useful for ArgumentException and its derivatives:

Now if someone refactors the name of the input parameter the exception will be kept up to date too.

It is also useful in some places where previously reflection had to be used to get the names of properties or parameters.

In your example nameof(T) gets the name of the type parameter — this can be useful too:

Another use of nameof is for enums — usually if you want the string name of an enum you use .ToString() :

This is actually relatively slow as .Net holds the enum value (i.e. 7 ) and finds the name at run time.

Instead use nameof :

Now .Net replaces the enum name with a string at compile time.

Yet another use is for things like INotifyPropertyChanged and logging — in both cases you want the name of the member that you’re calling to be passed to another method:

Another use-case where nameof feature of C# 6.0 becomes handy — Consider a library like Dapper which makes DB retrievals much easier. Albeit this is a great library, you need to hardcode property/field names within query. What this means is that if you decide to rename your property/field, there are high chances that you will forget to update query to use new field names. With string interpolation and nameof features, code becomes much easier to maintain and typesafe.

From the example given in link

without nameof

with nameof

Sateesh Pagolu's user avatar

Your question already expresses the purpose. You must see this might be useful for logging or throwing exceptions.

This is good. If I change the name of the variable, the code will break instead of returning an exception with an incorrect message.

Of course, the uses are not limited to this simple situation. You can use nameof whenever it would be useful to code the name of a variable or property.

The uses are manifold when you consider various binding and reflection situations. It’s an excellent way to bring what were run time errors to compile time.

Pang's user avatar

The most common use case I can think of is when working with the INotifyPropertyChanged interface. (Basically everything related to WPF and bindings uses this interface)

Take a look at this example:

As you can see in the old way we have to pass a string to indicate which property has changed. With nameof we can use the name of the property directly. This might not seem like a big deal. But image what happens when somebody changes the name of the property Foo . When using a string the binding will stop working, but the compiler will not warn you. When using nameof you get a compiler error that there is no property/argument with the name Foo .

Note that some frameworks use some reflection magic to get the name of the property, but now we have nameof this is no longer neccesary.

Patrick Hofman's user avatar

Most common usage will be in input validation, such as

In first case, if you refactor the method changing par parameter’s name, you’ll probably forget to change that in the ArgumentNullException. With nameof you don’t have to worry about that.

The ASP.NET Core MVC project uses nameof in the AccountController.cs and ManageController.cs with the RedirectToAction method to reference an action in the controller.

This translates to:

and takes takes the user to the ‘Index’ action in the ‘Home’ controller, i.e. /Home/Index .

Let’s say you need to print the name of a variable in your code. If you write:

and then if someone refactors the code and uses another name for myVar , he/she would have to look for the string value in your code and change it accordingly.

Instead, if you write:

It would help to refactor automatically!

Pang's user avatar

The MSDN article lists MVC routing (the example that really clicked the concept for me) among several others. The (formatted) description paragraph reads:

  • When reporting errors in code,
  • hooking up model-view-controller (MVC) links,
  • firing property changed events, etc.,

The accepted / top rated answers already give several excellent concrete examples.

As others have already pointed out, the nameof operator does insert the name that the element was given in the sourcecode.

I would like to add that this is a really good idea in terms of refactoring since it makes this string refactoring safe. Previously, I used a static method which utilized reflection for the same purpose, but that has a runtime performance impact. The nameof operator has no runtime performance impact; it does its work at compile time. If you take a look at the MSIL code you will find the string embedded. See the following method and its disassembled code.

However, that can be a drawback if you plan to obfuscate your software. After obfuscation the embedded string may no longer match the name of the element. Mechanisms that rely on this text will break. Examples for that, including but not limited to are: Reflection, NotifyPropertyChanged .

Determining the name during runtime costs some performance, but is safe for obfuscation. If obfuscation is neither required nor planned, I would recommend using the nameof operator.

Оператор nameof: Новая функция С# 6.0

Оператор nameof: Новая функция С# 6.0

3709

Введение

12 ноября 2014 в рамках конференции Connect () Microsoft презентовала Visual Studio 2015, которая имеет много новых и интересных возможностей тестирования для разработчиков. Microsoft анонсировала новую версию C# — C# 6.0, улучшенную и обновленную. Одно из нововведений функций C# 6.0 –оператор nameof.

Что такое оператор nameof

С введением оператора nameof теперь возможно избегать сложно закодированых строчек в коде. Оператор nameof принимает имя элементов кода и возвращает строчный литерал этого элемента. Параметры, которые принимает оператор nameof, включают имя класса и всех его членов, таких как: методы, переменные и константы.

Довольно удобно использовать строчные литералы, чтобы бросить ArgumentNullException (назвать аргумент винованым) и вызвать события PropertyChanged (чтоб назвать измененное свойство), но велика вероятность появления ошибки, потому что можно неправильно их записать или не восстановить после рефакторинга. Выражения оператора nameof являются особым видом строчного литерала, где компилятор проверяет, есть ли у Вас что-то с заданным именем и Visual Studio знает, куда он ссылается, поэтому навигация и рефакторинг будут работать легко.

Оператор nameof может быть полезным для разных сценариев, таких как INotifyPropertyChanged, ArgumentNullException и отображения.

Console .WriteLine( nameof (person)); // prints person

Console .WriteLine( nameof (x)); //prints x

public Operatornameof( string name) //constructor

throw new ArgumentNullException ( nameof (name)); // use of nameof Operator

Console .WriteLine( "Name: " + name);

private int _price;

public int price

return this ._price;

this ._price = value ;

PropertyChanged( this , new PropertyChangedEventArgs ( nameof ( this .price))); //// INotifyPropertyChanged

private void PropertyChanged( Operatornameof operatornameof1, PropertyChangedEventArgs propertyChangedEventArgs)

throw new NotImplementedException ();

Тема связана со специальностями:

Программа 1 с использованием Visual Studio 2013

public class operatornameof

public operatornameof( string name, string location, string age)

throw new ArgumentNullException ( "name" );

Console .WriteLine( " \n Name: " + name);

if (location == null )

throw new ArgumentNullException ( "location" );

Console .WriteLine( " Location: " + location);

throw new ArgumentNullException ( "age" );

Console .WriteLine( " Age: " + age);

static void Main( String [] args)

operatornameof p = new operatornameof ( "Abhishek" , "Ghaziabad" , "23" );

Видео курсы по схожей тематике:

Практикум курса C# Стартовый на примерах из GTA 5

Практикум курса C# Стартовый на примерах из GTA 5

Практики и инструменты DevOps

Практики и инструменты DevOps

Создание адаптивного сайта с Bootstrap 3

Создание адаптивного сайта с Bootstrap 3

Программа 1 с использованием Visual Studio 2015 Preview

public class Operatornameof

public Operatornameof( string name, string location, string age)

throw new ArgumentNullException ( nameof (name));

Console .WriteLine( "Name: " + name);

if (location == null )

throw new ArgumentNullException ( nameof (location));

Console .WriteLine( "Location: " + location);

throw new ArgumentNullException ( nameof (age));

Console .WriteLine( "Age: " + age);

static void Main( String [] args)

Operatornameof p = new Operatornameof ( "Abhishek" , "Ghaziabad" , "23" );

Программа 2 с использованием Visual Studio 2013

static void Main( string [] args)

details d = new details ();

Console .WriteLine( " \n Name: <0>" , d.Name);

Console .WriteLine( " Age: <0>" , d.Age);

private string _Name;

public int _Age;

public string Name

Программа 3 с использованием Visual Studio 2015 Preview

static void Main( string [] args)

details d = new details ();

Console .WriteLine( " <0>: <1>" , nameof ( details .Name), d.Name);

Console .WriteLine( " <0>: <1>" , nameof ( details .Age), d.Age);

public string Name < get ; set ; >= "Abhishek" ;

public int Age < get ; set ; >= 23;

Бесплатные вебинары по схожей тематике:

F# и функциональное программирование для C# разработчиков.

F# и функциональное программирование для C# разработчиков.

Возможности Vue.js для веб разработчика

Возможности Vue.js для веб разработчика

Пятнашки на C# для Android

Пятнашки на C# для Android

Из данной статьи Вы узнали, как использовать оператор nameof, чтобы избежать использования сложно закодированых строчек в коде. Надеемся, что Вам понравилась новая функция C# 6.0, введенная Microsoft.

Читать:
Как работает video downloadhelper

Похожие статьи