.NET Core Examples

Code Samples for .NET Core

Console Hello World

A simple console application that prints Hello, World! to the terminal.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Minimal Web API

Creating a minimal API endpoint that returns a list of products.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", () => new[]
{
    new { Id = 1, Name = "Laptop", Price = 999.99 },
    new { Id = 2, Name = "Smartphone", Price = 599.99 }
});

app.Run();

Entity Framework Core - CRUD

Basic CRUD operations using EF Core with an in‑memory database.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseInMemoryDatabase("ProductsDb");
}

// Sample usage
using var db = new AppDbContext();
db.Products.Add(new Product { Name = "Tablet", Price = 299.99M });
db.SaveChanges();

var product = db.Products.First();
Console.WriteLine($"{product.Name}: ${product.Price}");

gRPC Service Definition

Define a simple gRPC service that returns a greeting.

syntax = "proto3";

option csharp_namespace = "GrpcDemo";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

Async/Await with HttpClient

Fetch data asynchronously from a public API.

using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

async Task<string> GetJokeAsync()
{
    using var client = new HttpClient();
    var response = await client.GetStringAsync("https://official-joke-api.appspot.com/random_joke");
    var joke = JsonSerializer.Deserialize<dynamic>(response);
    return $"{joke.setup} - {joke.punchline}";
}

Console.WriteLine(await GetJokeAsync());