### Programa 'Hello, world!' básico en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/file-based-programs_source=recommendations Este snippet muestra el código C# más simple para imprimir 'Hello, world!' en la consola. Es un punto de partida fundamental para crear aplicaciones basadas en archivos. ```csharp Console.WriteLine("Hello, world!"); ``` -------------------------------- ### C# Range Expression Examples Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/operators/member-access-operators Provides comprehensive examples of various C# range expressions, including all values, start to end, start to end (exclusive), and counting from the end. ```csharp int[] oneThroughTen = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; Write(oneThroughTen, ..); Write(oneThroughTen, ..3); Write(oneThroughTen, 2..); Write(oneThroughTen, 3..5); Write(oneThroughTen, ^2..); Write(oneThroughTen, ..^3); Write(oneThroughTen, 3..^4); Write(oneThroughTen, ^4..^2); static void Write(int[] values, Range range) => Console.WriteLine($"{range}:\t{string.Join(", ", values[range])}"); // Sample output: // 0..^0: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 // 0..3: 1, 2, 3 // 2..^0: 3, 4, 5, 6, 7, 8, 9, 10 // 3..5: 4, 5 // ^2..^0: 9, 10 // 0..^3: 1, 2, 3, 4, 5, 6, 7 // 3..^4: 4, 5, 6 // ^4..^2: 7, 8 ``` -------------------------------- ### Realizar solicitud GET y obtener datos JSON Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/console-webapiclient Realiza una solicitud HTTP GET a la API de GitHub para obtener una lista de repositorios de la organización .NET Foundation. Utiliza HttpClient.GetStringAsync para recuperar el cuerpo de la respuesta como una cadena y luego lo imprime en la consola. ```csharp static async Task ProcessRepositoriesAsync(HttpClient client) { var json = await client.GetStringAsync( "https://api.github.com/orgs/dotnet/repos"); Console.Write(json); } ``` -------------------------------- ### Ubicación de artefactos de compilación temporales en Windows y Unix Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/file-based-programs_source=recommendations Muestra la estructura de directorios donde el host `dotnet` almacena los archivos ejecutables compilados para programas basados en archivos en diferentes sistemas operativos. Estas rutas indican los artefactos temporales generados. ```text AsciiArt succeeded (7.3s) → AppData\Local\Temp\dotnet\runfile\AsciiArt-85c58ae0cd68371711f06f297fa0d7891d0de82afde04d8c64d5f910ddc04ddc\bin\debug\AsciiArt.dll ``` ```text AsciiArt succeeded (7.3s) → Library/Application Support/dotnet/runfile/AsciiArt-85c58ae0cd68371711f06f297fa0d7891d0de82afde04d8c64d5f910ddc04ddc/bin/debug/AsciiArt.dll ``` -------------------------------- ### C# Open Interval Operator Examples Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/operators/member-access-operators Illustrates the use of open intervals with the C# `..` operator, showing how to create ranges from the start to an end, from a start to the end, and for the entire sequence. ```csharp int[] numbers = [0, 10, 20, 30, 40, 50]; int amountToDrop = numbers.Length / 2; int[] rightHalf = numbers[amountToDrop..]; Display(rightHalf); // output: 30 40 50 int[] leftHalf = numbers[..^amountToDrop]; Display(leftHalf); // output: 0 10 20 int[] all = numbers[..]; Display(all); // output: 0 10 20 30 40 50 void Display(IEnumerable xs) => Console.WriteLine(string.Join(" ", xs)); ``` -------------------------------- ### Instalación de Visual Studio Code Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials_source=recommendations Instrucciones para descargar e instalar la versión más reciente de Visual Studio Code desde su página principal. El sitio web detecta la plataforma del usuario y proporciona el enlace de descarga correcto para su sistema operativo. ```bash Descargue el instalador más reciente de la página principal de Visual Studio Code y haga doble clic para ejecutarlo. ``` -------------------------------- ### C# Example 2: Reference a library and delete it. Source: https://learn.microsoft.com/es-es/dotnet/csharp/misc/cs1684 This C# code references the library created in Example 1. It defines a class 'Ref' with methods to get instances of 'A' and 'C2'. A post-build command is used to delete the referenced DLL, setting up the condition for the CS1684 warning. ```csharp // CS1684_b.cs // compile with: /target:library /r:cs1684_a.dll // post-build command: del /f CS1684_a.dll using System; public class Ref { public static A GetA() { return new A(); } public static C2 GetC() { return new C2(); } } ``` -------------------------------- ### Ejecutar programa C# simple con .NET CLI Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/file-based-programs Este fragmento muestra cómo escribir un programa 'Hello, world!' básico en C# y ejecutarlo usando la CLI de .NET. La CLI compila y ejecuta el archivo de origen, creando artefactos en una carpeta temporal. ```csharp Console.WriteLine("Hello, world!"); ``` ```bash dotnet run AsciiArt.cs ``` -------------------------------- ### C# Creating Open-Ended Ranges Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/ranges-indexes_source=recommendations Demonstrates creating ranges that are open at the start, end, or both. It shows how to get all elements, the first four, and the last four elements, printing each resulting sub-array. ```csharp string[] allWords = words[..]; // contains "first" through "tenth". string[] firstPhrase = words[..4]; // contains "first" through "fourth" string[] lastPhrase = words[6..]; // contains "seventh", "eight", "ninth" and "tenth" // < first >< second >< third >< fourth >< fifth >< sixth >< seventh >< eighth >< ninth >< tenth > foreach (var word in allWords) Console.Write($"< {word} >"); Console.WriteLine(); // < first >< second >< third >< fourth > foreach (var word in firstPhrase) Console.Write($"< {word} >"); Console.WriteLine(); // < seventh >< eighth >< ninth >< tenth > foreach (var word in lastPhrase) Console.Write($"< {word} >"); Console.WriteLine(); ``` -------------------------------- ### Ejemplos de Uso de Código con Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/xmldoc/recommended-tags La etiqueta se usa para proporcionar un ejemplo de cómo usar un método, a menudo incluyendo la etiqueta para mostrar el código de ejemplo. ```xml This shows how to increment an integer. var index = 5; index++; ``` -------------------------------- ### C# Address-of Operator Example Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/language-specification/unsafe-code Illustrates using the address-of operator (&) to get the address of a variable 'i' and then assigning a value to the memory location pointed to by 'p'. The 'i' variable is considered definitely assigned after the '&i' operation. ```C# class Test { static void Main() { int i; unsafe { int* p = &i; *p = 123; } Console.WriteLine(i); } } ``` -------------------------------- ### Tutorial interactivo: Hello World en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials/branches-and-loops Un tutorial introductorio para aprender C# de forma interactiva. Escribe código C# 'Hello World' en el explorador y ve los resultados de la compilación y ejecución. ```csharp /* Tutorial interactivo 'Hello World' en C# */ System.Console.WriteLine("Hello, World!"); ``` -------------------------------- ### Instalar .NET SDK en Linux Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials Pasos para descargar e instalar el SDK de .NET en Linux. Se recomienda descargar el instalador desde la página oficial del SDK de .NET. ```shell bash # Descargue el instalador recomendado en la página de descarga del SDK de .NET # y haga doble clic para ejecutarlo. La página de descarga detecta la plataforma y recomienda el instalador más reciente para la plataforma. # Descargue el instalador más reciente de la página principal de Visual Studio Code y haga doble clic para ejecutarlo. Esa página también detecta tu plataforma y el vínculo debe ser correcto para tu sistema operativo. # Haga clic en el botón "Instalar" de la página de extensión C# DevKit. Se abre Visual Studio Code y se pregunta si desea instalar o habilitar la extensión. Seleccione "instalar". ``` -------------------------------- ### Complete Example: Indexed Properties in Excel Interop Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/interop/how-to-use-indexed-properties-in-com-interop-programming This is a full C# example demonstrating the usage of indexed properties to interact with Microsoft Excel. It includes setup for both older (2008) and newer (2010) C# versions, showing how to create an Excel application instance, add a workbook, make it visible, and set a cell's value. ```csharp // You must add a reference to Microsoft.Office.Interop.Excel to run // this example. using System; using Excel = Microsoft.Office.Interop.Excel; namespace IndexedProperties { class Program { static void Main(string[] args) { CSharp2010(); } static void CSharp2010() { var excelApp = new Excel.Application(); excelApp.Workbooks.Add(); excelApp.Visible = true; Excel.Range targetRange = excelApp.Range["A1"]; targetRange.Value = "Name"; } static void CSharp2008() { var excelApp = new Excel.Application(); excelApp.Workbooks.Add(Type.Missing); excelApp.Visible = true; Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing); targetRange.set_Value(Type.Missing, "Name"); // Or //targetRange.Value2 = "Name"; } } } ``` -------------------------------- ### Ejemplo de código 'Hola Mundo' en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/roslyn-sdk/get-started/syntax-analysis_source=recommendations Un programa C# básico que imprime "Hello World!" en la consola. Sirve como ejemplo de la estructura de código que la API de sintaxis puede analizar. ```csharp using System; using System.Collections.Generic; using System.Linq; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ``` -------------------------------- ### C# Unclosed Comment Example (CS1035) Source: https://learn.microsoft.com/es-es/dotnet/csharp/misc/cs1035 This C# code snippet demonstrates the CS1035 compiler error. The error occurs because the block comment starting with '/*' is not properly closed with '*/', leading to an unexpected end of file. ```csharp // CS1035.cs public class a { public static void Main() { } } /* // CS1035, needs closing comment ``` -------------------------------- ### Generic method with constraints in C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/generics/generic-methods Shows how to apply constraints to generic type parameters in C#. This example defines 'SwapIfGreater' which requires the type parameter 'T' to implement IComparable, allowing for comparison-based operations. ```csharp void SwapIfGreater(ref T lhs, ref T rhs) where T : System.IComparable { T temp; if (lhs.CompareTo(rhs) > 0) { temp = lhs; lhs = rhs; rhs = temp; } } ``` -------------------------------- ### Ejecución de un programa C# basado en archivos con .NET CLI Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/file-based-programs_source=recommendations Comando para compilar y ejecutar un archivo de código fuente C# (`AsciiArt.cs`) utilizando el CLI de .NET. El host `dotnet` maneja la compilación en una carpeta temporal y la ejecución del ejecutable resultante. ```bash dotnet run AsciiArt.cs ``` -------------------------------- ### Declare a sealed class (C#) Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/abstract-and-sealed-classes-and-class-members Provides an example of declaring a sealed class using the 'sealed' keyword in C#. Sealed classes cannot be used as base classes, preventing inheritance. ```csharp public sealed class D { // Class members here. } ``` -------------------------------- ### Instalación de componentes .NET en otras plataformas Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials_source=recommendations Instrucciones para descargar e instalar el SDK de .NET desde su página oficial, que detecta automáticamente la plataforma del usuario y recomienda el instalador adecuado. ```bash Descargue el instalador recomendado en la página de descarga del SDK de .NET y haga doble clic para ejecutarlo. ``` -------------------------------- ### Ejecutar la aplicación de consola .NET Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/console-webapiclient Este comando restaura automáticamente las dependencias de la aplicación, las compila si es necesario y luego ejecuta la aplicación de consola. Se espera que la salida sea 'Hello, World!'. ```bash dotnet run ``` -------------------------------- ### C# nameof Expression Usage Examples Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/language-specification/expressions Illustrates various use cases of the nameof operator in C#. It shows how to get the name of namespaces, types, variables, and members as constant strings. ```csharp using TestAlias = System.String; class Program { static void Main() { var point = (x: 3, y: 4); string n1 = nameof(System); // "System" string n2 = nameof(System.Collections.Generic); // "Generic" string n3 = nameof(point); // "point" string n4 = nameof(point.x); // "x" string n5 = nameof(Program); // "Program" string n6 = nameof(System.Int32); // "Int32" string n7 = nameof(TestAlias); // "TestAlias" string n8 = nameof(List); // "List" string n9 = nameof(Program.InstanceMethod); // "InstanceMethod" string n10 = nameof(Program.GenericMethod); // "GenericMethod" string n11 = nameof(Program.NestedClass); // "NestedClass" // Invalid // string x1 = nameof(List<>); // Empty type argument list // string x2 = nameof(List); // T is not in scope // string x3 = nameof(GenericMethod<>); // Empty type argument list // string x4 = nameof(GenericMethod); // T is not in scope // string x5 = nameof(int); // Keywords not permitted // Type arguments not permitted for method group // string x6 = nameof(GenericMethod); } void InstanceMethod() { } void GenericMethod() { string n1 = nameof(List); // "List" string n2 = nameof(T); // "T" } class NestedClass { } } ``` -------------------------------- ### Ejecutar programa .NET con argumentos de línea de comandos Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/top-level-statements_source=recommendations Este comando de la CLI de .NET demuestra cómo ejecutar un programa .NET y pasarle argumentos de línea de comandos. Los argumentos que siguen a `--` se pasan al programa. Útil para probar la entrada del programa. ```bash dotnet run -- Should I use top level statements in all my programs? ``` -------------------------------- ### Generic method returning an array in C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/generics/generic-methods Presents a generic method in C# that uses its type parameter 'T' as the return type. This specific example returns an array of type T, created from two input values. ```csharp T[] Swap(T a, T b) { return [b, a]; } ``` -------------------------------- ### Instalación de la extensión C# DevKit en Visual Studio Code Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials_source=recommendations Pasos para instalar la extensión C# DevKit dentro de Visual Studio Code. Al hacer clic en el botón 'Instalar' en la página de la extensión, se abrirá VS Code y se solicitará la confirmación de la instalación. ```bash Seleccione "instalar". ``` -------------------------------- ### C# Interval Operator Usage Examples Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/operators/member-access-operators Demonstrates various ways to use the C# interval operator `..` with arrays and strings, including specifying start and end points, and using negative indices from the end. ```csharp int[] numbers = [0, 10, 20, 30, 40, 50]; int start = 1; int amountToTake = 3; int[] subset = numbers[start..(start + amountToTake)]; Display(subset); // output: 10 20 30 int margin = 1; int[] inner = numbers[margin..^margin]; Display(inner); // output: 10 20 30 40 string line = "one two three"; int amountToTakeFromEnd = 5; Range endIndices = ^amountToTakeFromEnd..^0; string end = line[endIndices]; Console.WriteLine(end); // output: three void Display(IEnumerable xs) => Console.WriteLine(string.Join(" ", xs)); ``` -------------------------------- ### Crear un programa C# basado en archivos Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/file-based-programs_source=recommendations Este fragmento de código muestra cómo crear un programa C# básico contenido en un único archivo `*.cs`. Este enfoque simplifica el aprendizaje de C# y es ideal para utilidades de línea de comandos. El programa está diseñado para escribir texto como arte ASCII. ```csharp string asciiArt = ""; Console.WriteLine(asciiArt); ``` -------------------------------- ### C# CS3008 CLS Compliance Identifier Warning Source: https://learn.microsoft.com/es-es/dotnet/csharp/misc/cs3008 This C# code example demonstrates the CS3008 compiler warning. It shows a public static integer member `_a` which violates CLS compliance because it starts with an underscore. ```csharp // CS3008.cs using System; [assembly:CLSCompliant(true)] public class a { public static int _a = 0; // CS3008 // OK, private // private static int _a1 = 0; public static void Main() { } } ``` -------------------------------- ### C# Property Access Examples Source: https://learn.microsoft.com/es-es/dotnet/csharp/language-reference/language-specification/expressions Illustrates how to access properties in C#, including getting and setting values for static and instance properties on classes, structs, or interfaces. Compilation errors occur for write-only or read-only properties. ```csharp P // The get accessor of property P in the containing class or struct is invoked. A compile-time error occurs if P is write-only. If P is non-static, the instance expression is this. ``` ```csharp P = value // The set accessor of property P in the containing class or struct is invoked with the argument list (value). A compile-time error occurs if P is read-only. If P is non-static, the instance expression is this. ``` ```csharp T.P // The get accessor of property P in the containing class or struct T is invoked. A compile-time error occurs if P is non-static or if P is write-only. ``` ```csharp T.P = value // The set accessor of property P in the class or struct T is invoked with the argument list (value). A compile-time error occurs if P is non-static or if P is read-only. ``` ```csharp e.P // The get accessor of property P in the class, struct, or interface given by the type of E is invoked with the instance expression e. A binding failure occurs if P is static or if P is write-only. ``` ```csharp e.P = value // The set accessor of property P in the class, struct, or interface belonging to the type E is invoked with the instance expression e and argument list (value). A binding failure occurs if P is static or if P is read-only. ``` -------------------------------- ### Simulación de consola inicial de .NET C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/performance/ref-tutorial_source=recommendations Muestra la salida de la consola de una simulación que mide y muestra lecturas de temperatura, humedad, oxígeno y CO2, junto con información sobre intrusos y riesgo. ```console Press to start simulation Debounced measurements: Temp: 67.332 Humidity: 41.077% Oxygen: 21.097% CO2 (ppm): 404.906 Average measurements: Temp: 67.332 Humidity: 41.077% Oxygen: 21.097% CO2 (ppm): 404.906 Debounced measurements: Temp: 67.349 Humidity: 46.605% Oxygen: 20.998% CO2 (ppm): 408.707 Average measurements: Temp: 67.349 Humidity: 46.605% Oxygen: 20.998% CO2 (ppm): 408.707 ``` ```console Debounced measurements: Temp: 67.597 Humidity: 46.543% Oxygen: 19.021% CO2 (ppm): 429.149 Average measurements: Temp: 67.568 Humidity: 45.684% Oxygen: 19.631% CO2 (ppm): 423.498 Current intruders: 3 Calculated intruder risk: High Debounced measurements: Temp: 67.602 Humidity: 46.835% Oxygen: 19.003% CO2 (ppm): 429.393 Average measurements: Temp: 67.568 Humidity: 45.684% Oxygen: 19.631% CO2 (ppm): 423.498 Current intruders: 3 Calculated intruder risk: High ``` -------------------------------- ### Crear una aplicación de consola básica en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/classes_source=recommendations Este fragmento de código muestra cómo crear una aplicación de consola básica en C# utilizando el comando 'dotnet new console'. Es el punto de partida para el tutorial. ```bash dotnet new console ``` ```csharp // See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!"); ``` -------------------------------- ### C# Parse Code and Get Root Node Source: https://learn.microsoft.com/es-es/dotnet/csharp/roslyn-sdk/get-started/syntax-analysis Parses the provided C# code text into a syntax tree and retrieves the root node (CompilationUnitSyntax). This is the starting point for traversing the code's abstract syntax tree. ```csharp SyntaxTree tree = CSharpSyntaxTree.ParseText(programText); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); ``` -------------------------------- ### Instalación de requisitos previos con WinGet en Windows Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials_source=recommendations Utiliza el paquete de configuración de WinGet para instalar todos los requisitos previos necesarios para el desarrollo en .NET y C# en Windows. WinGet omitirá automáticamente los componentes que ya estén instalados en el sistema. ```powershell winget configure ..json ``` -------------------------------- ### C# Example: Asynchronous User Retrieval Source: https://learn.microsoft.com/es-es/dotnet/csharp/asynchronous-programming/async-scenarios_source=recommendations Shows how to retrieve user data asynchronously. It includes methods to get a single user by ID (`GetUserAsync`) and multiple users by a list of IDs (`GetUsersAsync` and `GetUsersAsyncByLINQ`). These methods utilize `Task.WhenAll` to efficiently run multiple asynchronous operations concurrently. ```csharp private static async Task GetUserAsync(int userId) { // Code omitted: // // Given a user Id {userId}, retrieves a User object corresponding // to the entry in the database with {userId} as its Id. return await Task.FromResult(new User() { id = userId }); } private static async Task> GetUsersAsync(IEnumerable userIds) { var getUserTasks = new List>(); foreach (int userId in userIds) { getUserTasks.Add(GetUserAsync(userId)); } return await Task.WhenAll(getUserTasks); } private static async Task GetUsersAsyncByLINQ(IEnumerable userIds) { var getUserTasks = userids.Select(id => GetUserAsync(id)).ToArray(); return await Task.WhenAll(getUserTasks); } ``` -------------------------------- ### LINQ Query to Filter Countries by Area in C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/linq/get-started/query-expression-basics_source=recommendations This C# example shows how to start a LINQ query using a 'from' clause to filter countries based on their area (greater than 20 sq km). The 'from' clause specifies the data source and a range variable. ```C# IEnumerable countryAreaQuery = from country in countries where country.Area > 20 //sq km select country; ``` -------------------------------- ### Recortar espacios en cadenas en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials/hello-world Ilustra el uso de los métodos TrimStart, TrimEnd y Trim para eliminar espacios en blanco al principio, al final o en ambos extremos de una cadena. Estos métodos devuelven nuevas cadenas y no modifican la original. ```csharp string greeting = " Hello World! "; Console.WriteLine($"[{greeting}]"); string trimmedGreeting = greeting.TrimStart(); Console.WriteLine($"[{trimmedGreeting}]"); trimmedGreeting = greeting.TrimEnd(); Console.WriteLine($"[{trimmedGreeting}]"); trimmedGreeting = greeting.Trim(); Console.WriteLine($"[{trimmedGreeting}]"); ``` -------------------------------- ### Ejecutar el programa C# en la CLI de .NET Source: https://learn.microsoft.com/es-es/dotnet/csharp/whats-new/tutorials/top-level-statements Muestra cómo ejecutar un programa C# compilado utilizando el comando 'dotnet run' con un argumento de pregunta. ```bash dotnet run -- Should I use top level statements in all my programs? Should I use top level statements in all my programs? Better not tell you now. ``` -------------------------------- ### AI Prompt for String to Number Conversion in C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number This section provides an example prompt for using AI tools like GitHub Copilot to generate C# code for converting a string to a number. The prompt specifically requests that no exception be thrown if the input string does not represent a number. ```text Show me how to parse a string as a number, but don't throw an exception if the input string doesn't represent a number. ``` -------------------------------- ### Descriptor de acceso get simple en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/using-properties_source=recommendations Este descriptor de acceso 'get' devuelve el valor de un campo privado '_name'. Las propiedades implementadas automáticamente se benefician de optimizaciones del compilador para lecturas de memoria eficientes. ```csharp class Employee { private string _name; // the name field public string Name => _name; // the Name property } ``` -------------------------------- ### Inicio de simulación y recopilación de datos base en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/performance/ref-tutorial_source=recommendations Este fragmento de código C# inicia una simulación después de que el usuario presiona Enter. Crea una instancia de la clase 'Room' y recopila datos iniciales de línea base llamando al método 'TakeMeasurements'. ```csharp Console.WriteLine("Press to start simulation"); Console.ReadLine(); var room = new Room("gallery"); var r = new Random(); int counter = 0; room.TakeMeasurements( m => { Console.WriteLine(room.Debounce); Console.WriteLine(room.Average); Console.WriteLine(); counter++; return counter < 20000; }); ``` -------------------------------- ### C# Read-Write Properties for Name and Age Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/how-to-declare-and-use-read-write-properties This C# code defines a `Person` class with private backing fields for `_name` and `_age`. It exposes these fields through public `Name` and `Age` properties, each with `get` and `set` accessors, making them read-write. The `ToString` method provides a formatted string representation of the `Person` object. ```csharp class Person { private string _name = "N/A"; private int _age = 0; // Declare a Name property of type string: public string Name { get { return _name; } set { _name = value; } } // Declare an Age property of type int: public int Age { get { return _age; } set { _age = value; } } public override string ToString() { return "Name = " + Name + ", Age = " + Age; } } public class Wrapper { private string _name = "N/A"; public string Name { get { return _name; } private set { _name = value; } } } class TestPerson { static void Main() { // Create a new Person object: Person person = new Person(); // Print out the name and the age associated with the person: Console.WriteLine($"Person details - {person}"); // Set some values on the person object: person.Name = "Joe"; person.Age = 99; Console.WriteLine($"Person details - {person}"); // Increment the Age property: person.Age += 1; Console.WriteLine($"Person details - {person}"); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: Person details - Name = N/A, Age = 0 Person details - Name = Joe, Age = 99 Person details - Name = Joe, Age = 100 */ ``` -------------------------------- ### Crear y ejecutar una nueva aplicación de consola .NET Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/console-teleprompter_source=recommendations Utilice la CLI de .NET para crear una nueva aplicación de consola y ejecute el comando 'dotnet run' para restaurar paquetes, compilar y ejecutar la aplicación. ```Bash dotnet new console dotnet run ``` -------------------------------- ### Define Abstract Property in C# Base Class Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/how-to-define-abstract-properties_source=recommendations This C# code defines an abstract base class 'Shape' with an abstract read-only property 'Area'. It includes a constructor, a settable 'Id' property, and overrides the 'ToString' method. The 'Area' property declaration specifies only a 'get' accessor, leaving its implementation to derived classes. ```csharp // compile with: csc -target:library abstractshape.cs public abstract class Shape { public Shape(string s) { // calling the set accessor of the Id property. Id = s; } public string Id { get; set; } // Area is a read-only property - only a get accessor is needed: public abstract double Area { get; } public override string ToString() { return $"{Id} Area = {Area:F2}"; } } ``` -------------------------------- ### C# Indexer with Enum Access Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/indexers/using-indexers Demonstrates an indexer that uses an enumeration type (`System.DayOfWeek`) as the index parameter. This provides a type-safe way to access elements, mapping day enum values to integer indices. The example includes a private array of `DayOfWeek` values and a `FindDayIndex` method. It only defines a `get` accessor. ```csharp using Day = System.DayOfWeek; class DayOfWeekCollection { Day[] days = [ Day.Sunday, Day.Monday, Day.Tuesday, Day.Wednesday, Day.Thursday, Day.Friday, Day.Saturday ]; // Indexer with only a get accessor with the expression-bodied definition: public int this[Day day] => FindDayIndex(day); private int FindDayIndex(Day day) { for (int j = 0; j < days.Length; j++) { if (days[j] == day) { return j; } } throw new ArgumentOutOfRangeException( nameof(day), $"Day {day} is not supported.\nDay input must be a defined System.DayOfWeek value."); } } ``` ```csharp var week = new DayOfWeekCollection(); Console.WriteLine(week[DayOfWeek.Friday]); try { Console.WriteLine(week[(DayOfWeek)43]); } catch (ArgumentOutOfRangeException e) { Console.WriteLine($"Not supported input: {e.Message}"); } ``` -------------------------------- ### Método TakeMeasurement en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/performance/ref-tutorial_source=recommendations Este método estático C# 'TakeMeasurement' dentro de la clase 'SensorMeasurement' se encarga de calcular las lecturas de CO2 y O2 en función de la habitación, los intrusos y un generador aleatorio. ```csharp public static SensorMeasurement TakeMeasurement(string room, int intruders) { return new SensorMeasurement { CO2 = (CO2Concentration + intruders * 10) + (20 * generator.NextDouble() - 10.0), O2 = (O2Concentration - intruders * 0.01) + (0.005 * generator.NextDouble() - 0.0025), ``` -------------------------------- ### C# Indexer with String Access Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/indexers/using-indexers Shows how to create an indexer that uses a string as the index parameter. This allows accessing elements by their string representation (e.g., day names). The example includes a private array of day abbreviations and a `FindDayIndex` method to locate the corresponding integer index. It only defines a `get` accessor. ```csharp // Using a string as an indexer value class DayCollection { string[] days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]; // Indexer with only a get accessor with the expression-bodied definition: public int this[string day] => FindDayIndex(day); private int FindDayIndex(string day) { for (int j = 0; j < days.Length; j++) { if (days[j] == day) { return j; } } throw new ArgumentOutOfRangeException( nameof(day), $"Day {day} is not supported.\nDay input must be in the form \"Sun\", \"Mon\", etc"); } } ``` ```csharp var week = new DayCollection(); Console.WriteLine(week["Fri"]); try { Console.WriteLine(week["Made-up day"]); } catch (ArgumentOutOfRangeException e) { Console.WriteLine($"Not supported input: {e.Message}"); } ``` -------------------------------- ### Agregar referencias a bibliotecas de Office en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/interop/walkthrough-office-programming_source=recommendations Instrucciones para agregar referencias a las bibliotecas de interoperabilidad de Excel y Word en un proyecto de C# de Visual Studio. ```text 1. En el **Explorador de soluciones** , haga clic con el botón derecho en el nombre del proyecto y luego seleccione **Agregar referencia**. 2. En la pestaña **Ensamblados** , seleccione **Microsoft.Office.Interop.Excel** y **Microsoft.Office.Interop.Word**. 3. Seleccione **Aceptar**. ``` -------------------------------- ### Equivalencia de propiedad de C# con métodos get/set separados Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/how-to-declare-and-use-read-write-properties Presenta el código equivalente para la operación de incremento de una propiedad si se hubieran utilizado métodos 'get' y 'set' separados en lugar de la sintaxis de propiedades. ```csharp person.SetAge(person.GetAge() + 1); ``` -------------------------------- ### Comentar llamadas a Autofit en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/interop/walkthrough-office-programming Este snippet muestra cómo comentar las llamadas a la función 'Autofit' al final del método 'DisplayInExcel' en un proyecto C#. Esto es parte del proceso para restaurar las dependencias de PIA. ```csharp // Autofit(); // Autofit(); ``` -------------------------------- ### Tutorial interactivo: Trabajar con números en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/tour-of-csharp/tutorials/branches-and-loops Explora los tipos numéricos en C# mediante un tutorial interactivo. Escribe código C# en el explorador y observa los resultados de la compilación y ejecución. ```csharp /* Tutorial interactivo sobre tipos numéricos en C# */ // Escriba su código C# aquí para trabajar con números. ``` -------------------------------- ### Convert Byte Array to Hex String using Convert.ToHexString (.NET 5+) Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types This example shows how to convert a byte array to a hexadecimal string using the `Convert.ToHexString` method, which was introduced in .NET 5.0. This method provides a more direct way to get a contiguous hexadecimal string without hyphens. Dependencies include `System` for `Console`. ```csharp byte[] array = {0x64, 0x6f, 0x74, 0x63, 0x65, 0x74}; string hexValue = Convert.ToHexString(array); Console.WriteLine(hexValue); /*Output: 646f74636574 */ ``` -------------------------------- ### Propiedad C# con descriptor de acceso 'init' Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/properties_source=recommendations Presenta una propiedad 'FirstName' con un descriptor de acceso 'init'. Esto permite que la propiedad se establezca durante la inicialización del objeto o dentro de los constructores, proporcionando flexibilidad en la asignación inicial en comparación con las propiedades de solo lectura. ```csharp public class Person { public Person() { } public Person(string firstName) => FirstName = firstName; public string? FirstName { get; init; } // Omitted for brevity. } ``` -------------------------------- ### Convert Hex String to Float (C#) Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types This example shows how to convert a hexadecimal string representation of a float into an actual float value. It first parses the hex string into a `uint` using `uint.Parse` with `AllowHexSpecifier`, then converts this `uint` into a byte array, and finally uses `BitConverter.ToSingle` to get the float value. Dependencies include `System` for `Console` and `BitConverter`. ```csharp string hexString = "43480170"; uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier); byte[] floatVals = BitConverter.GetBytes(num); float f = BitConverter.ToSingle(floatVals, 0); Console.WriteLine($"float convert = {f}"); // Output: 200.0056 ``` -------------------------------- ### C# Span Indexing and Ranges Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/ranges-indexes Demonstrates how to use C# indexes and ranges with Span to access portions of a sequence. Shows slicing with start..end, ..end, start.., and start..^end syntax. ```csharp Span x_x = numbers[x..^x]; Console.WriteLine($"\tnumbers[x..^x] starts with {x_x[0]} and ends with {x_x[^1]}"); Console.WriteLine("numbers[..x] means numbers[0..x] and numbers[x..] means numbers[x..^0]"); Span start_x = numbers[..x]; Span zero_x = numbers[0..x]; Console.WriteLine($"\t{start_x[0]}..{start_x[^1]} is the same as {zero_x[0]}..{zero_x[^1]}"); Span z_end = numbers[z..]; Span z_zero = numbers[z..^0]; Console.WriteLine($"\t{z_end[0]}..{z_end[^1]} is the same as {z_zero[0]}..{z_zero[^1]}"); ``` -------------------------------- ### Start Simulation and Collect Baseline Data in C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/performance/ref-tutorial This C# code snippet initializes a simulation by creating a 'Room' object and taking initial baseline measurements. It outputs debounced and average measurements to the console for a fixed number of iterations, demonstrating the initial phase of the simulation. ```C# Console.WriteLine("Press to start simulation"); Console.ReadLine(); var room = new Room("gallery"); var r = new Random(); int counter = 0; room.TakeMeasurements( m => { Console.WriteLine(room.Debounce); Console.WriteLine(room.Average); Console.WriteLine(); counter++; return counter < 20000; }); ``` -------------------------------- ### C# Example 4: Reference modified library and trigger warning. Source: https://learn.microsoft.com/es-es/dotnet/csharp/misc/cs1684 This C# code references the libraries from previous examples. It calls a method that depends on class 'C2' (which was removed in Example 3). This compilation triggers the CS1684 warning because the reference to 'C2' is now invalid. ```csharp // CS1684_d.cs // compile with: /reference:cs1684_a.dll /reference:cs1684_b.dll // CS1684 expected class Tester { public static void Main() { Ref.GetA().Test(); } } ``` -------------------------------- ### Ejemplo de uso de la CLI de .NET para comandos de proceso Source: https://learn.microsoft.com/es-es/dotnet/csharp/fundamentals/tutorials/file-based-programs Demuestra cómo ejecutar un programa C# con argumentos de línea de comandos, incluidos mensajes entrecomillados y una opción de retraso. ```bash AsciiArt.cs "This is line one" "This is another line" "This is the last line" AsciiArt.cs --delay 1000 ``` -------------------------------- ### Instanciar un delegado con un método existente en C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate_source=recommendations Crea una instancia del delegado NotifyCallback asignándole el método Notify. Esto vincula el delegado a una implementación de método específica. ```csharp // Create an instance of the delegate. NotifyCallback del1 = new NotifyCallback(Notify); ``` -------------------------------- ### CS0183 Compiler Warning Example in C# Source: https://learn.microsoft.com/es-es/dotnet/csharp/misc/cs0183 This C# code example demonstrates the CS0183 compiler warning. The warning occurs when the 'is' operator is used with a value type, as the check is always true. The example shows a conditional statement that will never be reached. ```csharp // CS0183.cs // compile with: /W:1 using System; public class Test { public static void F(Int32 i32, String str) { if (str is Object) // OK Console.WriteLine( "str is an object" ); else Console.WriteLine( "str is not an object" ); if (i32 is Object) // CS0183 Console.WriteLine( "i32 is an object" ); else Console.WriteLine( "i32 is not an object" ); // never reached } public static void Main() { F(0, "CS0183"); F(120, null); } } ``` -------------------------------- ### Crear una nueva aplicación de consola .NET Source: https://learn.microsoft.com/es-es/dotnet/csharp/tutorials/console-webapiclient Este comando crea los archivos de inicio para una aplicación básica 'Hola mundo' en .NET. El nombre del proyecto se establece en 'WebAPIClient'. ```bash dotnet new console --name WebAPIClient ``` -------------------------------- ### Propiedad C# de solo lectura con descriptor de acceso privado set Source: https://learn.microsoft.com/es-es/dotnet/csharp/programming-guide/classes-and-structs/how-to-declare-and-use-read-write-properties Define una propiedad pública 'Name' con un descriptor de acceso 'get' público y un descriptor de acceso 'set' privado. Esto permite leer la propiedad desde cualquier lugar, pero solo permite modificarla desde dentro de la clase. ```csharp public string Name { get { return _name; } private set { _name = value; } } ``` -------------------------------- ### C# Compiler Error CS0030: Type Conversion Example Source: https://learn.microsoft.com/es-es/dotnet/csharp/misc/cs0030 This C# code example demonstrates the CS0030 compiler error. The error occurs because there's no implicit or explicit conversion defined between the 'iii' type and 'int'. To resolve this, user-defined conversion operators (commented out in the example) need to be implemented. ```csharp // CS0030.cs namespace x { public class iii { /* public static implicit operator iii(int aa) { return null; } public static implicit operator int(iii aa) { return 0; } */ public static iii operator ++(iii aa) { return (iii)0; // CS0030 // uncomment the conversion routines to resolve CS0030 } public static void Main() { } } } ``` -------------------------------- ### Crear una nueva aplicación de consola .NET Source: https://learn.microsoft.com/es-es/dotnet/csharp/advanced-topics/reflection-and-attributes/attribute-tutorial_source=recommendations Este comando crea los archivos de proyecto básicos de .NET para una nueva aplicación de consola. No requiere dependencias externas, pero se recomienda ejecutar `dotnet restore` para asegurarse de que todas las dependencias necesarias se recuperan antes de compilar o ejecutar el proyecto. ```bash dotnet new console ```