Elysia Tools

Explora herramientas, ejemplos, explicaciones visuales y guías temáticas en un solo espacio claro.

Categorías populares

Temas

Idioma
ZHESPTRUFRDEEN

Elysia Tools

Navegación

Lenguajes de programación

Ejemplos C#: excepciones, LINQ y límites de bucle

Resuelva tres ejemplos C# acotados con entradas explícitas y resultados comprobables.

Ejemplos

Entradas de esta colección

CódigocsharpSimple

Hola Mundo C#

Programa Hola Mundo básico y conceptos fundamentales .NET con sintaxis moderna de C#

Dificultad

2/10

Tiempo estimado

10 min

Etiquetas

csharp, .net, beginner

Requisitos previos

Basic programming concepts

csharp
using System;
using System.Collections.Generic;
using System.Linq;

// 1. Basic Hello World
class Program1
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

// 2. Hello World with variable
class Program2
{
    static void Main()
    {
        string message = "Hello, World!";
        Console.WriteLine(message);
    }
}

// 3. Hello World with function
class Program3
{
    static string GetGreeting()
    {
        return "Hello, World!";
    }

    static void Main()
    {
        Console.WriteLine(GetGreeting());
    }
}

// 4. Hello World with parameters
class Program4
{
    static string GetGreeting(string name)
    {
        return $"Hello, {name}!";
    }

    static void Main()
    {
        Console.WriteLine(GetGreeting("World"));
        Console.WriteLine(GetGreeting("C#"));
    }
}

// 5. Hello World with class
class Greeter
{
    private string _message;

    public Greeter(string message = "Hello, World!")
    {
        _message = message;
    }

    public void DisplayGreeting()
    {
        Console.WriteLine(_message);
    }
}

class Program5
{
    static void Main()
    {
        var greeter = new Greeter();
        greeter.DisplayGreeting();
    }
}

// 6. Hello World with user input
class Program6
{
    static void Main()
    {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine() ?? "World";
        Console.WriteLine($"Hello, {name}!");
    }
}

// 7. Hello World multiple times
class Program7
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Hello, World! {i}");
        }
    }
}

// 8. Hello World with collection
class Program8
{
    static void Main()
    {
        var greetings = new List<string> { "Hello", "Bonjour", "Hola", "Ciao", "こんにちは" };

        foreach (var greeting in greetings)
        {
            Console.WriteLine($"{greeting}, World!");
        }
    }
}

// 9. Hello World with dictionary
class Program9
{
    static void Main()
    {
        var greetings = new Dictionary<string, string>
        {
            { "en", "Hello" },
            { "es", "Hola" },
            { "fr", "Bonjour" },
            { "de", "Hallo" },
            { "ja", "こんにちは" }
        };

        foreach (var greeting in greetings)
        {
            Console.WriteLine($"{greeting.Value}, World! ({greeting.Key})");
        }
    }
}

// 10. Hello World with exception handling
class Program10
{
    static void Main()
    {
        try
        {
            var numbers = new List<int> { 10, 0, 5 };
            for (int i = 0; i < numbers.Count; i++)
            {
                Console.WriteLine($"100 / {numbers[i]} = {100 / numbers[i]}");
            }
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            Console.WriteLine("Hello, Exception World!");
        }
    }
}

// Basic data types examples
class Program11
{
    static void Main()
    {
        // Primitive types
        int integer = 42;
        double floatingPoint = 3.14;
        float singlePrecision = 3.14f;
        decimal money = 99.99m;
        bool boolValue = true;
        char character = '@';
        string text = "Hello, C#";

        Console.WriteLine($"Integer: {integer}, Type: {integer.GetType()}");
        Console.WriteLine($"Double: {floatingPoint}, Type: {floatingPoint.GetType()}");
        Console.WriteLine($"Float: {singlePrecision}, Type: {singlePrecision.GetType()}");
        Console.WriteLine($"Decimal: {money}, Type: {money.GetType()}");
        Console.WriteLine($"Boolean: {boolValue}, Type: {boolValue.GetType()}");
        Console.WriteLine($"Char: {character}, Type: {character.GetType()}");
        Console.WriteLine($"String: {text}, Type: {text.GetType()}");

        // Nullable types
        int? nullableInt = null;
        DateTime? nullableDate = null;

        Console.WriteLine($"Nullable int has value: {nullableInt.HasValue}");
        Console.WriteLine($"Nullable date: {nullableDate ?? DateTime.MinValue}");
    }

    // Control flow examples
    static void ControlFlowExamples()
    {
        int age = 18;

        if (age >= 18)
        {
            Console.WriteLine("You are an adult");
        }
        else
        {
            Console.WriteLine("You are a minor");
        }

        // Switch expression (C# 8.0+)
        string dayType = DateTime.Now.DayOfWeek switch
        {
            DayOfWeek.Saturday => "Weekend",
            DayOfWeek.Sunday => "Weekend",
            _ => "Weekday"
        };

        Console.WriteLine($"Today is a {dayType}");

        // Loop examples
        var fruits = new List<string> { "apple", "banana", "cherry" };
        foreach (var fruit in fruits)
        {
            Console.WriteLine($"I like {fruit}");
        }

        // LINQ examples
        var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
        var squaredNumbers = numbers.Select(n => n * n).ToList();

        Console.WriteLine($"Even numbers: {string.Join(", ", evenNumbers)}");
        Console.WriteLine($"Squared numbers: {string.Join(", ", squaredNumbers)}");
    }
}
CódigocsharpIntermedio

Programación Orientada a Objetos C#

Conceptos OOP avanzados incluyendo herencia, interfaces, genéricos y patrones de diseño

Dificultad

7/10

Tiempo estimado

40 min

Etiquetas

csharp, oop, design patterns, advanced

Requisitos previos

Basic C# syntax, Object-oriented concepts

csharp
using System;
using System.Collections.Generic;

// 1. Classes and Inheritance
public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    protected Animal(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public virtual void MakeSound()
    {
        Console.WriteLine($"{Name} makes a sound");
    }

    public virtual void DisplayInfo()
    {
        Console.WriteLine($"{Name} is {Age} years old");
    }
}

public class Dog : Animal
{
    public string Breed { get; set; }

    public Dog(string name, int age, string breed) : base(name, age)
    {
        Breed = breed;
    }

    public override void MakeSound()
    {
        Console.WriteLine($"{Name} barks: Woof!");
    }

    public void WagTail()
    {
        Console.WriteLine($"{Name} is wagging its tail");
    }
}

public class Cat : Animal
{
    public bool IsIndoor { get; set; }

    public Cat(string name, int age, bool isIndoor) : base(name, age)
    {
        IsIndoor = isIndoor;
    }

    public override void MakeSound()
    {
        Console.WriteLine($"{Name} meows: Meow!");
    }

    public void Purr()
    {
        Console.WriteLine($"{Name} is purring");
    }
}

// 2. Interfaces
public interface IShape
{
    double CalculateArea();
    double CalculatePerimeter();
    void DisplayShapeInfo();
}

public interface IMovable
{
    void Move(int distanceX, int distanceY);
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }

    public double CalculatePerimeter()
    {
        return 2 * Math.PI * Radius;
    }

    public void DisplayShapeInfo()
    {
        Console.WriteLine($"Circle - Radius: {Radius}, Area: {CalculateArea():F2}");
    }
}

public class Rectangle : IShape, IMovable
{
    public double Width { get; set; }
    public double Height { get; set; }
    public double X { get; private set; }
    public double Y { get; private set; }

    public Rectangle(double width, double height, double x = 0, double y = 0)
    {
        Width = width;
        Height = height;
        X = x;
        Y = y;
    }

    public double CalculateArea()
    {
        return Width * Height;
    }

    public double CalculatePerimeter()
    {
        return 2 * (Width + Height);
    }

    public void DisplayShapeInfo()
    {
        Console.WriteLine($"Rectangle - Width: {Width}, Height: {Height}, Area: {CalculateArea():F2}");
    }

    public void Move(int distanceX, int distanceY)
    {
        X += distanceX;
        Y += distanceY;
        Console.WriteLine($"Rectangle moved to ({X}, {Y})");
    }
}

// 3. Abstract Classes
public abstract class Vehicle
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }

    protected Vehicle(string brand, string model, int year)
    {
        Brand = brand;
        Model = model;
        Year = year;
    }

    public abstract void Start();
    public abstract void Stop();

    public virtual void DisplayInfo()
    {
        Console.WriteLine($"{Year} {Brand} {Model}");
    }
}

public class Car : Vehicle
{
    public int NumberOfDoors { get; set; }

    public Car(string brand, string model, int year, int numberOfDoors)
        : base(brand, model, year)
    {
        NumberOfDoors = numberOfDoors;
    }

    public override void Start()
    {
        Console.WriteLine($"{Brand} {Model} engine started");
    }

    public override void Stop()
    {
        Console.WriteLine($"{Brand} {Model} engine stopped");
    }

    public void OpenTrunk()
    {
        Console.WriteLine("Trunk opened");
    }
}

// 4. Generics
public class GenericContainer<T>
{
    private T _item;

    public GenericContainer(T item)
    {
        _item = item;
    }

    public T GetItem()
    {
        return _item;
    }

    public void SetItem(T item)
    {
        _item = item;
    }

    public override string ToString()
    {
        return $"Container with: {_item}";
    }
}

public class Calculator
{
    public T Add<T>(T a, T b) where T : struct
    {
        if (a is int intA && b is int intB)
            return (T)(object)(intA + intB);

        if (a is double doubleA && b is double doubleB)
            return (T)(object)(doubleA + doubleB);

        throw new NotSupportedException("Only int and double operations are supported");
    }
}

// 5. Generic Repository Pattern
public interface IRepository<T> where T : class
{
    T GetById(int id);
    IEnumerable<T> GetAll();
    void Add(T entity);
    void Update(T entity);
    void Delete(int id);
}

public class InMemoryRepository<T> : IRepository<T> where T : class
{
    private readonly Dictionary<int, T> _storage = new();

    public T GetById(int id)
    {
        return _storage.TryGetValue(id, out var entity) ? entity : null;
    }

    public IEnumerable<T> GetAll()
    {
        return _storage.Values;
    }

    public void Add(T entity)
    {
        int id = _storage.Count + 1;
        _storage[id] = entity;
    }

    public void Update(T entity)
    {
        // In a real implementation, you'd update by entity ID
        Console.WriteLine($"Entity updated: {entity}");
    }

    public void Delete(int id)
    {
        _storage.Remove(id);
    }
}

// 6. Design Patterns - Singleton
public sealed class Logger
{
    private static readonly Lazy<Logger> _instance = new Lazy<Logger>(() => new Logger());
    private readonly List<string> _logs = new List<string>();

    private Logger()
    {
    }

    public static Logger Instance => _instance.Value;

    public void Log(string message)
    {
        string logEntry = $"{DateTime.Now}: {message}";
        _logs.Add(logEntry);
        Console.WriteLine(logEntry);
    }

    public void PrintAllLogs()
    {
        Console.WriteLine("=== All Logs ===");
        foreach (var log in _logs)
        {
            Console.WriteLine(log);
        }
    }
}

// 7. Factory Pattern
public interface IPaymentProcessor
{
    void ProcessPayment(decimal amount);
}

public class CreditCardProcessor : IPaymentProcessor
{
    public void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Processing credit card payment of ${amount}");
    }
}

public class PayPalProcessor : IPaymentProcessor
{
    public void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Processing PayPal payment of ${amount}");
    }
}

public static class PaymentProcessorFactory
{
    public static IPaymentProcessor CreateProcessor(string paymentType)
    {
        return paymentType.ToLower() switch
        {
            "creditcard" => new CreditCardProcessor(),
            "paypal" => new PayPalProcessor(),
            _ => throw new ArgumentException($"Unknown payment type: {paymentType}")
        };
    }
}

// 8. Observer Pattern
public interface IObserver<T>
{
    void Update(T data);
}

public interface ISubject<T>
{
    void Subscribe(IObserver<T> observer);
    void Unsubscribe(IObserver<T> observer);
    void Notify(T data);
}

public class WeatherStation : ISubject<float>
{
    private readonly List<IObserver<float>> _observers = new List<IObserver<float>>();
    private float _temperature;

    public float Temperature
    {
        get => _temperature;
        set
        {
            _temperature = value;
            Notify(_temperature);
        }
    }

    public void Subscribe(IObserver<float> observer)
    {
        _observers.Add(observer);
    }

    public void Unsubscribe(IObserver<float> observer)
    {
        _observers.Remove(observer);
    }

    public void Notify(float data)
    {
        foreach (var observer in _observers)
        {
            observer.Update(data);
        }
    }
}

public class TemperatureDisplay : IObserver<float>
{
    private readonly string _name;

    public TemperatureDisplay(string name)
    {
        _name = name;
    }

    public void Update(float temperature)
    {
        Console.WriteLine($"{_name} display shows: {temperature}°C");
    }
}

// Example usage
class Program
{
    static void Main()
    {
        // Inheritance demo
        var dog = new Dog("Buddy", 3, "Golden Retriever");
        dog.DisplayInfo();
        dog.MakeSound();
        dog.WagTail();

        // Interface demo
        var circle = new Circle(5.0);
        circle.DisplayShapeInfo();

        var rectangle = new Rectangle(4.0, 6.0);
        rectangle.DisplayShapeInfo();
        rectangle.Move(10, 15);

        // Generics demo
        var intContainer = new GenericContainer<int>(42);
        var stringContainer = new GenericContainer<string>("Hello Generics!");

        Console.WriteLine(intContainer);
        Console.WriteLine(stringContainer);

        // Singleton demo
        var logger = Logger.Instance;
        logger.Log("Application started");
        logger.Log("User logged in");

        // Factory demo
        var creditCardProcessor = PaymentProcessorFactory.CreateProcessor("creditcard");
        creditCardProcessor.ProcessPayment(99.99m);

        // Observer demo
        var weatherStation = new WeatherStation();
        var display1 = new TemperatureDisplay("Living Room");
        var display2 = new TemperatureDisplay("Kitchen");

        weatherStation.Subscribe(display1);
        weatherStation.Subscribe(display2);
        weatherStation.Temperature = 25.5f;
        weatherStation.Temperature = 26.0f;
    }
}
CódigocsharpComplejo

Características Modernas C#

Características modernas de C# 8-11 incluyendo records, pattern matching y programación async

Dificultad

8/10

Tiempo estimado

45 min

Etiquetas

csharp, modern c#, async, advanced, csharp9, csharp10, csharp11

Requisitos previos

Advanced C#, .NET Core/.NET 5+, Asynchronous programming concepts

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// 1. Records (C# 9.0+)
// Positional record
public record Person(string FirstName, string LastName, int Age);

// Record with methods
public record Employee(int Id, string Name, decimal Salary)
{
    public decimal AnnualBonus { get; init; } = 0;

    public decimal TotalCompensation => Salary + AnnualBonus;

    public virtual void GiveRaise(decimal amount)
    {
        Console.WriteLine($"{Name} got a raise of ${amount}");
    }
}

// Record inheritance
public record Manager(int Id, string Name, decimal Salary, string Department)
    : Employee(Id, Name, Salary)
{
    public override void GiveRaise(decimal amount)
    {
        Console.WriteLine($"Manager {Name} in {Department} got a raise of ${amount}");
    }
}

// 2. Pattern Matching (C# 8.0+)
public class PatternMatching
{
    public static string GetDescription(object value)
    {
        return value switch
        {
            null => "Null value",
            int i when i < 0 => "Negative integer",
            int i when i > 0 => "Positive integer",
            int i => "Zero",
            string s when string.IsNullOrEmpty(s) => "Empty string",
            string s when s.Length > 10 => "Long string",
            string s => $"String: {s}",
            DateTime dt when dt > DateTime.Now => "Future date",
            DateTime dt when dt < DateTime.Now => "Past date",
            DateTime dt => "Today",
            Person p when p.Age < 18 => $"{p.FirstName} is a minor",
            Person p => $"{p.FirstName} is {p.Age} years old",
            _ => "Unknown type"
        };
    }

    public static decimal CalculateDiscount(Product product)
    {
        return product switch
        {
            { Category: "Electronics", Price: > 1000 } => product.Price * 0.1m,
            { Category: "Electronics", Price: > 500 } => product.Price * 0.05m,
            { Category: "Books", Price: var price } when price < 20 => price * 0.15m,
            { Category: "Clothing", InStock: false } => 0m,
            { Price: var price } when price > 100 => price * 0.2m,
            _ => 0m
        };
    }
}

public class Product
{
    public string Name { get; set; } = "";
    public string Category { get; set; } = "";
    public decimal Price { get; set; }
    public bool InStock { get; set; } = true;
}

// 3. Nullable Reference Types (C# 8.0+)
#nullable enable

public class UserService
{
    private readonly Dictionary<int, User> _users = new();

    public User? GetUserById(int id)
    {
        return _users.TryGetValue(id, out var user) ? user : null;
    }

    public string GetUserEmail(int id)
    {
        var user = GetUserById(id);
        return user?.Email ?? throw new InvalidOperationException("User not found");
    }

    public void PrintUserName(int id)
    {
        var user = GetUserById(id);
        if (user != null)
        {
            Console.WriteLine($"User: {user.Name}");
        }
        else
        {
            Console.WriteLine("User not found");
        }
    }
}

public class User
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string? Email { get; set; }
    public List<string>? Tags { get; set; }
}

// 4. Async Programming (C# 8.0+)
public class AsyncService
{
    public async Task<string> FetchDataAsync(string url)
    {
        Console.WriteLine($"Starting fetch from {url}");

        // Simulate async operation
        await Task.Delay(1000);

        Console.WriteLine($"Completed fetch from {url}");
        return $"Data from {url}";
    }

    public async Task<IEnumerable<string>> FetchMultipleUrlsAsync(IEnumerable<string> urls)
    {
        var tasks = urls.Select(url => FetchDataAsync(url));
        var results = await Task.WhenAll(tasks);
        return results;
    }

    public async IAsyncEnumerable<string> StreamDataAsync(IEnumerable<int> numbers)
    {
        foreach (var number in numbers)
        {
            await Task.Delay(100); // Simulate async work
            yield return $"Processed: {number}";
        }
    }

    public async Task ProcessDataStreamAsync()
    {
        var numbers = Enumerable.Range(1, 10);
        await foreach (var result in StreamDataAsync(numbers))
        {
            Console.WriteLine(result);
        }
    }
}

// 5. Expression-bodied members (C# 6.0+)
public class Calculator
{
    public double Add(double a, double b) => a + b;
    public double Subtract(double a, double b) => a - b;
    public double Multiply(double a, double b) => a * b;
    public double Divide(double a, double b) => b != 0 ? a / b : throw new DivideByZeroException();

    public static double Pi => Math.PI;
    public static double E => Math.E;
}

// 6. Tuples and deconstruction (C# 7.0+)
public class TupleExamples
{
    public static (int Min, int Max, double Average) CalculateStats(IEnumerable<int> numbers)
    {
        var list = numbers.ToList();
        return (list.Min(), list.Max(), list.Average());
    }

    public static void DeconstructionExample()
    {
        var (min, max, avg) = CalculateStats(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
        Console.WriteLine($"Min: {min}, Max: {max}, Avg: {avg}");
    }

    public static (string FirstName, string LastName) ParseName(string fullName)
    {
        var parts = fullName.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        return (parts.Length > 0 ? parts[0] : "", parts.Length > 1 ? parts[1] : "");
    }
}

// 7. Local functions (C# 7.0+)
public class LocalFunctionExamples
{
    public static int Factorial(int n)
    {
        int ComputeFactorial(int x)
        {
            return x <= 1 ? 1 : x * ComputeFactorial(x - 1);
        }

        return ComputeFactorial(n);
    }

    public static bool IsPalindrome(string text)
    {
        bool CheckPalindrome(string s, int left, int right)
        {
            return left >= right || s[left] == s[right] && CheckPalindrome(s, left + 1, right - 1);
        }

        var cleanText = string.Concat(text.Where(char.IsLetterOrDigit)).ToLower();
        return CheckPalindrome(cleanText, 0, cleanText.Length - 1);
    }
}

// 8. Switch expressions (C# 8.0+)
public class SwitchExpressionExamples
{
    public static string GetDayType(DayOfWeek day) => day switch
    {
        DayOfWeek.Saturday => "Weekend",
        DayOfWeek.Sunday => "Weekend",
        _ => "Weekday"
    };

    public static decimal CalculateTax(decimal amount, string state) => state.ToUpper() switch
    {
        "CA" => amount * 0.0875m,
        "NY" => amount * 0.08m,
        "TX" => amount * 0.0625m,
        "FL" => amount * 0.06m,
        _ => 0m
    };

    public static string GetGradeLetter(int score) => score switch
    {
        >= 90 => "A",
        >= 80 => "B",
        >= 70 => "C",
        >= 60 => "D",
        _ => "F"
    };
}

// 9. Using declarations (C# 8.0+)
public class UsingDeclarationExamples
{
    public static async Task ProcessFilesAsync()
    {
        await foreach (var line in ReadLinesAsync("example.txt"))
        {
            Console.WriteLine($"Read: {line}");
        }
    }

    private static async IAsyncEnumerable<string> ReadLinesAsync(string filename)
    {
        using var reader = new StreamReader(filename);
        string? line;

        while ((line = await reader.ReadLineAsync()) != null)
        {
            yield return line;
        }
    }
}

// 10. Static local functions (C# 8.0+)
public class StaticLocalFunctionExample
{
    public static int Calculate(int x, int y)
    {
        static int Add(int a, int b) => a + b;
        static int Multiply(int a, int b) => a * b;

        return Add(x, y) + Multiply(x, y);
    }
}

// 11. Target-typed new expressions (C# 9.0+)
public class TargetTypedNew
{
    private readonly List<string> _names = new();
    private readonly Dictionary<int, string> _dictionary = new();

    public void AddName(string name) => _names.Add(name);
    public int Count => _names.Count;
}

// 12. Top-level statements (C# 9.0+)
// This file itself demonstrates top-level statements

// Example usage
class Program
{
    static async Task Main()
    {
        // Records demo
        var person = new Person("John", "Doe", 30);
        Console.WriteLine(person);

        var employee = new Employee(1, "Jane Smith", 75000m) { AnnualBonus = 5000m };
        Console.WriteLine($"Total compensation: {employee.TotalCompensation:C}");

        // Pattern matching demo
        Console.WriteLine(PatternMatching.GetDescription(person));

        var product = new Product { Name = "Laptop", Category = "Electronics", Price = 1200m, InStock = true };
        decimal discount = PatternMatching.CalculateDiscount(product);
        Console.WriteLine($"Discount: ${discount}");

        // Tuples demo
        TupleExamples.DeconstructionExample();
        var (firstName, lastName) = TupleExamples.ParseName("John Doe");
        Console.WriteLine($"First: {firstName}, Last: {lastName}");

        // Async demo
        var asyncService = new AsyncService();
        string data = await asyncService.FetchDataAsync("https://api.example.com");
        Console.WriteLine(data);

        var urls = new[] { "https://api1.com", "https://api2.com", "https://api3.com" };
        var results = await asyncService.FetchMultipleUrlsAsync(urls);
        foreach (var result in results)
        {
            Console.WriteLine(result);
        }

        await asyncService.ProcessDataStreamAsync();

        // Switch expressions demo
        Console.WriteLine($"Today is a {SwitchExpressionExamples.GetDayType(DateTime.Now.DayOfWeek)}");
        Console.WriteLine($"Grade for 85: {SwitchExpressionExamples.GetGradeLetter(85)}");

        // Local functions demo
        Console.WriteLine($"5! = {LocalFunctionExamples.Factorial(5)}");
        Console.WriteLine($"'racecar' is palindrome: {LocalFunctionExamples.IsPalindrome("racecar")}");

        // Using declarations demo
        // Uncomment to test with actual file
        // await UsingDeclarationExamples.ProcessFilesAsync();

        Console.WriteLine("Modern C# features demonstration completed!");
    }
}

Herramientas

Herramientas que suelen usarse con este ejemplo

Relacionado

Colecciones de ejemplos relacionadas

Relacionado

Temas relacionados

Guía de uso de la herramienta

Contexto para entender esta colección de ejemplos

Resumen

Use «Hola Mundo C#» para los ejercicios. Siga solo el bloque indicado; otras tarjetas tratan funciones y dependencias diferentes.

Elegir el ejemplo mínimo

Una colección no es una aplicación única. Aísle la función o clase y elija su entrada antes de copiarla a un proyecto de prueba.

Hay varias clases con Main. Elija una o configure el objeto de inicio; no trate toda la colección como un único programa.

Cómo funciona

  1. 1Lea la tarjeta y siga los valores declarados. La página muestra código; no ejecuta este lenguaje.

Casos límite y errores frecuentes

  • Alcance del resultado

    Son expectativas derivadas del código, no salidas registradas de compilación o ejecución. Entrada interactiva, reloj, archivos, hilos, servicios y frameworks quedan fuera.

Ejemplos

1. Seguir Program10

Cómo usarlo

En «Hola Mundo C#», localice Program10. Use numbers = [10,0,5] y siga únicamente las operaciones indicadas en el mismo orden.

Resultado

Esperado: 100/10=10; DivideByZeroException; finally. La excepción sale del bucle; no procesa el tercer divisor, pero finally se ejecuta.

2. Seguir Program11.ControlFlowExamples: Where / Select

Cómo usarlo

En «Hola Mundo C#», localice Program11.ControlFlowExamples: Where / Select. Use numbers = 1..10 y siga únicamente las operaciones indicadas en el mismo orden.

Resultado

Esperado: [2,4,6,8,10]; [1,4,9,16,25,36,49,64,81,100]. El filtro conserva pares; map transforma toda la lista original.

3. Seguir Program7

Cómo usarlo

En «Hola Mundo C#», localice Program7. Use i=1; i<=5; i++ y siga únicamente las operaciones indicadas en el mismo orden.

Resultado

Esperado: 1,2,3,4,5. El límite superior se incluye: cinco iteraciones.

Tema

Revisión e integración de un componente de sorteos autoalojado

Revisa la configuración, las respuestas de ejemplo, la legibilidad y el diseño adaptable antes de entregar los archivos y las pruebas de integración del sorteo.

Tema

Modelos farmacocineticos docentes y revision de resultados

Explora formulas farmacocineticas, supuestos de modelo y coherencia de resultados para docencia o QA, sin dar dosis ni consejo clinico.

Tema

Herramientas de cifrado clásico y moderno

Practica cifrados seguros para educación o CTF comparando transformaciones clásicas reversibles con cifrado moderno y sus límites de seguridad.

Tema

Revisión de una lección Markdown interactiva y entrega sin conexión

Revisa contenido y configuración, ensaya el HTML exportado sin conexión y separa archivos del público de fuentes privadas.

Inicio
Herramientas3215
Ejemplos593
Visualizaciones472
Visores de archivos103
Temas239
Etiquetas333
Imágenes, audio y video657

Herramientas de procesamiento, conversión y optimización de imágenes, audio y video

Matemáticas, fechas y finanzas647

Calculadoras, herramientas numéricas, lógica de fechas, estadística y finanzas

Diseño y color298

Herramientas de color, maquetación, gráficos, estilo visual y apoyo al diseño

Texto y redacción209

Herramientas de redacción, limpieza, formato, extracción y análisis de texto

Desarrollo y Web194

Utilidades para desarrolladores, red, depuración web y automatización

Conversión y codificación175

Herramientas de conversión de formatos, archivos, unidades, archivos comprimidos y codificación

Lanzamiento de un cuestionario de captación y entrega de contactos
Textos conmemorativos: revisión familiar y entrega para impresión
Hábitos privados: copia, restauración y revisión antes de compartir
De artículo a borradores de X y LinkedIn: revisión factual y entrega
Revisión de una lección Markdown interactiva y entrega sin conexión

© 2026 Elysia Tools. Todos los derechos reservados.

DocumentaciónPreciosAcerca deTérminos de servicioPolítica de privacidadCookiesContacto

Development

Formateador de Código

Formatear código en varios lenguajes

Lenguajes de programación

Ejemplos de F#

Ejemplos esenciales de programación F# para programación funcional y desarrollo .NET