C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Nameof OperatorC# NameOf operator is used to get name of a variable, class or method. It returns a simple string as a result. In error prone code, it is useful to capture a method name, in which error occurred. We can use it for logging, validating parameters, checking events etc. Note: if we want to get fully qualified name, we can use typeof expression along with nameof operator.Let's see an example that implements nameof operator. C# Nameof Operator Example 1using System; namespace CSharpFeatures { class NameOfExample { public static void Main(string[] args) { string name = "TheDeveloperBlog"; // Accessing name of variable and method Console.WriteLine("Variable name is: "+nameof(name)); Console.WriteLine("Method name is: "+nameof(show)); } static void show() { // code statements } } } Output: Variable name is: name Method name is: show We can also use it to get method name in which exception is occurred. See, the following example. C# Nameof Operator Example 2using System; namespace CSharpFeatures { class NameOfExample { int[] arr = new int[5]; public static void Main(string[] args) { NameOfExample ex = new NameOfExample(); try { ex.show(ex.arr); } catch(Exception e) { Console.WriteLine(e.Message); // Displaying method name that throws the exception Console.WriteLine("Method name is: "+nameof(ex.show)); } } int show(int[] a) { a[6] = 12; return a[6]; } } } Output: Index was outside the bounds of the array. Method name is: show
Next TopicC# Dictionary Initializer
|