AYUDA .NET

C# Nameof (Cómo funciona para los desarrolladores)

Actualizado marzo 6, a. m.
Compartir:

El operador 'nameof', introducido en C# 6.0, es una construcción en tiempo de compilación diseñada para abordar el reto de referirse a los elementos del programa por sus nombres y romper silenciosamente el comportamiento en tiempo de ejecución. Su objetivo principal es eliminar la necesidad de cadenas codificadas, ofreciendo un enfoque más fácil de mantener y resistente a errores. En este artículo, exploraremos el operador nameof en C# y también introduciremos IronPDF NuGet para generar documentos PDF mediante programación.

Sintaxis básica del operador "nameof

La sintaxis fundamental del operador "nameof" es sencilla. Toma un elemento como argumento y devuelve su nombre como cadena. Considere el siguiente ejemplo:

static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
Shared Sub Main()
 'string name
  Dim myVariable As String = NameOf(myVariable)
End Sub
VB   C#

En este caso, "nameof(miVariable)' produce la entrada de cadena "miVariable". El operador puede aplicarse a diversos elementos del código, como variables, tipos, miembros, etc.

Ventajas del operador "nameof

Mantenimiento del código

Una de las ventajas más destacadas del operador "nameof" es su impacto positivo en el mantenimiento del código. En lugar de codificar los nombres como cadenas, los desarrolladores pueden utilizar "nameof" para que las referencias se actualicen automáticamente cuando cambien los nombres.

static void Main()
{
// Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.");
// Using nameof for improved maintainability
Logger.Log($"Error: The variable '{nameof(myVariable)}' is null.");
}
static void Main()
{
// Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.");
// Using nameof for improved maintainability
Logger.Log($"Error: The variable '{nameof(myVariable)}' is null.");
}
Shared Sub Main()
' Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.")
' Using nameof for improved maintainability
Logger.Log($"Error: The variable '{NameOf(myVariable)}' is null.")
End Sub
VB   C#

Seguridad en tiempo de compilación

nameof' mejora la seguridad en tiempo de compilación al eliminar el riesgo de errores tipográficos o incoherencias en los nombres. Cualquier error ortográfico o modificación del nombre de una variable provoca un error en tiempo de compilación, lo que reduce las posibilidades de que se produzcan problemas en tiempo de ejecución.

static void Main()
{
// Compile-time error if 'myVariable' is misspelled
string myVariable = nameof(myVariabell);
}
static void Main()
{
// Compile-time error if 'myVariable' is misspelled
string myVariable = nameof(myVariabell);
}
Shared Sub Main()
' Compile-time error if 'myVariable' is misspelled
Dim myVariable As String = NameOf(myVariabell)
End Sub
VB   C#

Apoyo a la refactorización

El operador "nameof" se integra a la perfección con las herramientas de refactorización, proporcionando una experiencia sin complicaciones a la hora de renombrar variables, tipos o miembros. Todas las referencias 'nameof' se actualizan automáticamente.

static void Main()
{
// Before renaming local variable 'myVariable' to 'newVariable'
string myVariable = nameof(myVariable);
// After renaming local variable  'myVariable' to 'newVariable'
string newVariable = nameof(newVariable);
}
static void Main()
{
// Before renaming local variable 'myVariable' to 'newVariable'
string myVariable = nameof(myVariable);
// After renaming local variable  'myVariable' to 'newVariable'
string newVariable = nameof(newVariable);
}
Shared Sub Main()
' Before renaming local variable 'myVariable' to 'newVariable'
Dim myVariable As String = NameOf(myVariable)
' After renaming local variable  'myVariable' to 'newVariable'
Dim newVariable As String = NameOf(newVariable)
End Sub
VB   C#

Depuración mejorada

Durante la depuración, 'nameof' hace que el código sea más informativo y legible. Las sentencias de registro, los mensajes de excepción y otras salidas de depuración se vuelven concisas y contextualmente relevantes.

static void Main()
{
// Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
// Using nameof for improved debugging 
throw new ArgumentNullException(nameof(myVariable), "The variable cannot be null.");
}
static void Main()
{
// Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
// Using nameof for improved debugging 
throw new ArgumentNullException(nameof(myVariable), "The variable cannot be null.");
}
Shared Sub Main()
' Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
' Using nameof for improved debugging 
Throw New ArgumentNullException(NameOf(myVariable), "The variable cannot be null.")
End Sub
VB   C#

Aquí el throw new ArgumentNullException nameof lanza una excepción si la variable no está declarada.

Casos prácticos del operador "nameof

Reflexión

Cuando se trabaja con reflection, el operador 'nameof' simplifica la obtención de los nombres de tipos, propiedades o métodos sin necesidad de utilizar cadenas codificadas.

Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Dim type As Type = GetType([MyClass])
Dim typeName As String = NameOf([MyClass])
VB   C#

La clase de ejemplo MyClass puede ser una cadena codificada, pero podemos usar reflection para obtener el nombre de la clase dinámicamente. El tipo de nombre de la variable tiene el nombre de la clase y luego se utiliza la palabra clave nameof para obtener el nombre de una instancia de la clase. No son el mismo nombre.

Registro y gestión de excepciones

nameof' resulta muy útil para registrar sentencias y mensajes de excepción, haciéndolos más legibles y menos propensos a errores.

Logger.Log($"Error: The property '{nameof(MyClass.MyProperty)}' is out of range.");
Logger.Log($"Error: The property '{nameof(MyClass.MyProperty)}' is out of range.");
Logger.Log($"Error: The property '{NameOf([MyClass].MyProperty)}' is out of range.")
VB   C#

Ejemplo

En este ejemplo, crearemos una clase simple que representa a una Persona, y utilizaremos el operador nameof para mejorar el registro y los mensajes de error.

using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
    //method name
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing."); // display string
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public string DoSomething()
{
}
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string
        person.LastName = "Doe"; // string
        // Display the full name string again
        person.DisplayFullName();
    }
}
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
    //method name
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing."); // display string
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public string DoSomething()
{
}
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string
        person.LastName = "Doe"; // string
        // Display the full name string again
        person.DisplayFullName();
    }
}
Imports System
Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	'method name
	Public Sub DisplayFullName()
		If String.IsNullOrEmpty(FirstName) String.IsNullOrEmpty(LastName) Then
			LogError($"Invalid name: {NameOf(FirstName)} or {NameOf(LastName)} is missing.") ' display string
		Else
			Console.WriteLine($"Full Name: {FirstName} {LastName}")
		End If
	End Sub
	Public Function DoSomething() As String
	End Function
	Private Sub LogError(ByVal errorMessage As String)
		Console.ForegroundColor = ConsoleColor.Red
		Console.WriteLine($"Error: {errorMessage}")
		Console.ResetColor()
	End Sub
End Class
Friend Class Program
	Shared Sub Main()
		' Create an instance of the Person class
		Dim person As New Person()
		' Attempt to display the full name
		person.DisplayFullName()
		' Set the properties
		person.FirstName = "John" ' string
		person.LastName = "Doe" ' string
		' Display the full name string again
		person.DisplayFullName()
	End Sub
End Class
VB   C#

Explicación

  1. Tenemos una clase Persona con las propiedades FirstName y LastName y un método llamado DisplayFullName que comprueba si ambas propiedades están establecidas antes de mostrar el nombre completo.
  2. Dentro del nombre del método DisplayFullName, utilizamos nameof(Nombre) y nombre de(Apellido) para referirse a los nombres de las propiedades como literales de cadena. Esto mejora la legibilidad del código y garantiza que, si los nombres de las propiedades cambian, tanto la definición de la propiedad como el mensaje de error correspondiente se actualicen automáticamente durante la compilación.
  3. El método LogError aprovecha nameof para incluir el nombre de la propiedad dinámicamente en el mensaje de error.
  4. En el método Main, creamos una instancia de la clase Persona, intentamos mostrar el nombre completo sin definir las propiedades y, a continuación, definimos la propiedad y volvemos a mostrar el nombre completo.

    La cadena pública DoSomething puede realizar alguna lógica de negocio utilizando el operador nameof.

    Cuando ejecute este programa, verá que el mensaje de error del compilador incorpora dinámicamente los nombres de las propiedades, proporcionando más contexto y facilitando la identificación de la propiedad que falta:

    C# Nombre (Cómo Funciona Para Desarrolladores): Figura 1 - Evento Cambio de Propiedad

    Este ejemplo demuestra cómo el operador nameof mejora la mantenibilidad del código actualizando automáticamente las referencias cuando cambian los nombres de las propiedades y mejora los mensajes de error con detalles más informativos durante el desarrollo.

Presentación de IronPDF

IronPDF es una biblioteca PDF en C# de Iron Software que puede utilizarse como generador y lector de PDF. Aquí presentamos la funcionalidad básica. Para más información, consulte la documentación.

La característica más destacada de IronPDF es su HTML a PDF conservando sus diseños y estilos. Genera archivos PDF a partir de contenido web, por lo que es ideal para informes, facturas y documentación. Los archivos HTML, las URL y las cadenas HTML se pueden convertir a PDF sin problemas.

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

Instalación

IronPDF puede instalarse mediante la consola del gestor de paquetes NuGet o el gestor de paquetes de Visual Studio.

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

C# Nombre (Cómo funciona para los desarrolladores): Figura 2 - Instale IronPDF utilizando NuGet Package Manager buscando "ironpdf" en la barra de búsqueda de NuGet Package Manager.

namespace OrderBy;
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf"); 
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
    }
}
namespace OrderBy;
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf"); 
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
    }
}
Imports System

Namespace OrderBy
	Friend Class Person
		Public Property FirstName() As String
		Public Property LastName() As String
		Public Sub DisplayFullName()
			If String.IsNullOrEmpty(FirstName) String.IsNullOrEmpty(LastName) Then
				LogError($"Invalid name: {NameOf(FirstName)} or {NameOf(LastName)} is missing.")
			Else
				Console.WriteLine($"Full Name: {FirstName} {LastName}")
			End If
		End Sub
		Public Sub PrintPdf()
			Console.WriteLine("Generating PDF using IronPDF.")
			Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>"
	ignore ignore ignore ignore ignore ignore ignore var pdfDocument = New ChromePdfRenderer()
			pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf")
		End Sub
		Private Sub LogError(ByVal errorMessage As String)
			Console.ForegroundColor = ConsoleColor.Red
			Console.WriteLine($"Error: {errorMessage}")
			Console.ResetColor()
		End Sub
	End Class
	Friend Class Program
		Shared Sub Main()
			' Create an  instance of the Person class
			Dim person As New Person()
			' Attempt to display the full name
			person.DisplayFullName()
			' Set the properties
			person.FirstName = "John" ' string literal
			person.LastName = "Doe" ' string literal
			' Display the full name again
			person.DisplayFullName()
		End Sub
	End Class
End Namespace
VB   C#

Aquí se utiliza IronPDF para generar un PDF utilizando las variables locales content y pdfDocument que se pueden ver en el método PrintPdf.

Salida

C# Nombre (Cómo funciona para los desarrolladores): Figura 3 - Salida del programa

Generación de PDF

C# Nombre (Cómo funciona para los desarrolladores): Figura 4 - Salida PDF

Licencias (prueba gratuita disponible)

IronPDF. Esta clave debe colocarse en appsettings.json.

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

Proporcione su correo electrónico para obtener una licencia de prueba.

Conclusión

El operador "nameof" de C# se ha convertido en un elemento básico para los desarrolladores que buscan un código más limpio, seguro y fácil de mantener. Su capacidad para mejorar la legibilidad del código, unida a la seguridad en tiempo de compilación y a un soporte de refactorización sin fisuras, lo convierten en una herramienta indispensable en el kit de herramientas del desarrollador de C#. A medida que la comunidad de desarrolladores sigue adoptando y aprovechando el operador "nameof", está llamado a desempeñar un papel fundamental en la configuración del futuro de la programación en C#. IronPDF es un práctico paquete NuGet que se puede utilizar para generar archivos PDF de forma rápida y sencilla.

< ANTERIOR
Operador C# (Cómo funciona para desarrolladores)
SIGUIENTE >
HashSet C# (Cómo funciona para desarrolladores)

¿Listo para empezar? Versión: 2024.8 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,439,034 Ver licencias >