💡 𝗨𝘀𝗲 𝗻𝗮𝗺𝗲𝗼𝗳() 𝘁𝗼 𝗰𝗼𝗻𝘃𝗲𝗿𝘁 𝗮𝗻 𝗲𝗻𝘂𝗺 𝘁𝗼 𝗮 𝘀𝘁𝗿𝗶𝗻𝗴

💡 C# Tips

✔️ The ToString function, which was inherited from the System.Object. value is converted into its string representation using the Object class.

✔️Introduced in C# 6.0, the 𝗻𝗮𝗺𝗲𝗼𝗳() keyword is used to retrieve a variable, type, or member's name as a string at compile time. It's beneficial to keep your code refactor-friendly.

✔️The ideal method for converting an enum to a string is nameof(). This is because nameof() is assessed at compile time and will inject a constant string literal, whereas ToString() is evaluated at runtime. This means that nameof() is more efficient and can help your code run faster.

  • Here is a simple example, I have used.

Article content

✔️Benchmarking results of ToString() vs NameOf() methods:

Article content

As we can see, the nameof method requires no memory allocation and is 100 times faster than the ToString function.

Thank you Ankit Panwar.. its very great concept

Like
Reply

To view or add a comment, sign in

More articles by Ankit Panwar

Explore content categories