The nameof keyword in C#



The nameof operator returns a string literal of an element that can be a variable, type or member.

For example, the following is our variable −

var vehicle = "motorbike";

To get the string literal, use nameof −

nameof(vehicle);

The following is the code to implement nameof keyword −

Example

 Live Demo

using System; public class Program {    static void Main() {       var vehicle = "motorbike";       Console.WriteLine(nameof(vehicle));       var time = DateTime.Now.ToLocalTime();       Console.WriteLine(nameof(time));       var a = false;       Console.WriteLine(nameof(a));    } }

Output

vehicle time a
Updated on: 2020-06-22T13:47:39+05:30

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements