Convert Figma logo to code with AI

dotnet logosamples

Sample code referenced by the .NET documentation

3,342
5,053
3,342
81

Top Related Projects

14,331

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.

14,915

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.

20,851

.NET news, announcements, release notes, and more!

17,679

This repo is used for servicing PR's for .NET Core 2.1 and 3.1. Please visit us at https://github.com/dotnet/runtime

18,892

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.

Quick Overview

The dotnet/samples repository on GitHub contains a collection of sample code and projects that demonstrate the capabilities and usage of the .NET platform. These samples cover a wide range of topics, including web development, desktop applications, mobile apps, and more, providing developers with a valuable resource for learning and exploring the .NET ecosystem.

Pros

  • Comprehensive Coverage: The repository offers a diverse set of samples that cover a wide range of .NET technologies and scenarios, making it a valuable resource for developers of all skill levels.
  • Active Maintenance: The repository is actively maintained by the .NET team, ensuring that the samples are up-to-date and reflect the latest developments in the .NET platform.
  • Community Contributions: The repository welcomes contributions from the .NET community, allowing developers to share their own samples and learn from the work of others.
  • Detailed Documentation: Each sample is accompanied by detailed documentation, including instructions for running and understanding the code, making it easier for developers to get started.

Cons

  • Overwhelming Variety: The sheer number of samples in the repository can be overwhelming, especially for newcomers to .NET, making it challenging to find the most relevant samples for their needs.
  • Varying Quality: While the majority of the samples are well-written and maintained, the quality can vary, as the repository is open to community contributions.
  • Outdated Samples: Some of the older samples may not reflect the latest best practices or use the most up-to-date versions of .NET libraries and tools.
  • Limited Guidance: While the documentation is generally good, some samples may lack detailed explanations or step-by-step guides, making it harder for developers to understand and apply the concepts.

Code Examples

Since the dotnet/samples repository is a collection of various .NET projects and samples, it does not contain a single code library. However, here are a few examples of the types of code samples you might find in the repository:

Web API Example

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}

This code snippet demonstrates a simple Web API controller that returns a list of weather forecasts.

WinForms Example

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Hello, World!");
    }
}

This code snippet shows a basic WinForms application with a button that displays a "Hello, World!" message when clicked.

Blazor WebAssembly Example

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

This code snippet demonstrates a simple Blazor WebAssembly application that displays a "Hello, World!" message and a survey prompt.

Getting Started

Since the dotnet/samples repository is a collection of various .NET projects and samples, there is no single "getting started" guide. However, here are some general steps to get started with the repository:

  1. Clone the Repository: Start by cloning the dotnet/samples repository to your local machine using Git:

    git clone https://github.com/dotnet/samples.git
    
  2. Explore the Samples: Navigate to the cloned repository and browse the various directories and subdirectories to find samples that are relevant to your interests or needs. Each sample typically has a README file that provides instructions for running and understanding the code.

  3. Build and Run the Samples: Depending on the sample, you may need to restore NuGet packages, build the project, and run the application. The README file for each sample should provide detailed instructions on how to do this.

  4. Customize and Experiment: Once you've run the samples, try

Competitor Comparisons

14,331

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.

Pros of dotnet

  • More comprehensive and official repository for .NET development
  • Includes source code for .NET runtime and libraries
  • Provides a centralized hub for .NET-related resources and documentation

Cons of dotnet

  • Larger and more complex repository, potentially overwhelming for beginners
  • May contain more advanced topics that are not immediately relevant for new developers
  • Updates and changes might be more frequent, requiring users to stay up-to-date

Code Comparison

samples:

// Simple console application
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

dotnet:

// More advanced example from CoreCLR
public static unsafe int Main(string[] args)
{
    fixed (char* pArgs = args.Length > 0 ? args[0] : null)
    {
        return RuntimeAugments.CallMain(MainMethod, pArgs, args.Length);
    }
}

The samples repository focuses on simpler, beginner-friendly examples, while dotnet includes more complex, low-level code used in the .NET runtime itself.

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.

Pros of aspnetcore

  • Comprehensive framework for building web applications and services
  • Actively maintained with frequent updates and new features
  • Extensive documentation and community support

Cons of aspnetcore

  • Larger codebase, potentially more complex for beginners
  • Focused specifically on web development, less versatile for other .NET projects

Code Comparison

aspnetcore:

app.MapGet("/", () => "Hello World!");
app.MapPost("/api/data", (MyData data) => {
    // Process data
});
app.Run();

samples:

Console.WriteLine("Hello World!");
var result = MyMethod();
Console.WriteLine($"Result: {result}");

Summary

aspnetcore is a robust framework for web development, offering a wide range of features and active maintenance. However, it may be overwhelming for beginners and is less suitable for non-web projects. samples, on the other hand, provides a variety of smaller, focused examples across different .NET technologies, making it easier for learners to grasp specific concepts. The code comparison illustrates the web-centric nature of aspnetcore versus the more general-purpose examples in samples.

14,915

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.

Pros of runtime

  • Comprehensive implementation of .NET runtime and core libraries
  • Highly optimized for performance and efficiency
  • Extensive documentation and active community support

Cons of runtime

  • Steeper learning curve due to complex codebase
  • Requires more system resources for development and testing
  • Less beginner-friendly compared to samples

Code Comparison

runtime:

public static unsafe int Main(string[] args)
{
    if (!TypeLoader.Initialize())
        return -1;
    return RuntimeEntryPoint.MainInner(args);
}

samples:

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
}

The runtime code snippet shows a more complex entry point with low-level operations, while the samples code demonstrates a simple "Hello World" program, highlighting the difference in complexity between the two repositories.

runtime focuses on core .NET functionality and performance optimization, making it suitable for advanced developers and those working on the .NET framework itself. samples, on the other hand, provides practical examples and tutorials, making it ideal for beginners and those learning .NET development.

20,851

.NET news, announcements, release notes, and more!

Pros of core

  • More comprehensive and official .NET runtime repository
  • Contains the core runtime, libraries, and SDK components
  • Offers deeper insights into .NET internals and development

Cons of core

  • Larger and more complex codebase, potentially overwhelming for beginners
  • Less focused on providing ready-to-use code examples
  • Requires more in-depth knowledge of .NET architecture

Code Comparison

samples:

// From dotnet/samples/csharp/getting-started/console-teleprompter/Program.cs
static async Task ShowTeleprompter()
{
    var words = ReadFrom("sampleQuotes.txt");
    foreach (var line in words)
    {
        Console.Write(line);
        if (!string.IsNullOrWhiteSpace(line))
        {
            await Task.Delay(200);
        }
    }
}

core:

// From dotnet/core/src/libraries/System.Console/src/System/Console.cs
public static ConsoleColor ForegroundColor
{
    get { return ConsolePal.ForegroundColor; }
    set { ConsolePal.ForegroundColor = value; }
}

The samples repository focuses on providing practical, self-contained examples for developers to learn and use .NET features. In contrast, the core repository contains the actual implementation of .NET runtime and libraries, offering a deeper look into the framework's internals but requiring more expertise to navigate and understand.

17,679

This repo is used for servicing PR's for .NET Core 2.1 and 3.1. Please visit us at https://github.com/dotnet/runtime

Pros of corefx

  • Comprehensive core framework implementation
  • Deeper insight into .NET internals and performance optimizations
  • More extensive API coverage and functionality

Cons of corefx

  • Steeper learning curve for beginners
  • Less focused on educational examples
  • Larger codebase, potentially overwhelming for newcomers

Code Comparison

samples:

public static async Task Main(string[] args)
{
    Console.WriteLine("Hello World!");
    await Task.Delay(1000);
}

corefx:

public static class Console
{
    public static void WriteLine(string value)
    {
        // Complex implementation details
    }
}

Summary

samples is designed to provide clear, concise examples for learning and reference, making it ideal for beginners and those looking for quick implementation guides. It offers a wide range of topics but with less depth than corefx.

corefx, on the other hand, is the core framework implementation, providing in-depth functionality and performance optimizations. It's more suitable for advanced developers looking to understand the inner workings of .NET or contribute to the framework itself.

While samples focuses on readability and simplicity, corefx prioritizes robustness and efficiency, often at the cost of immediate comprehension for newcomers to the .NET ecosystem.

18,892

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.

Pros of Roslyn

  • Provides deep insights into C# and Visual Basic compilers
  • Offers powerful APIs for code analysis and manipulation
  • Enables creation of custom analyzers and code fixes

Cons of Roslyn

  • Steeper learning curve due to complexity
  • Larger codebase, potentially overwhelming for beginners
  • Focused on compiler internals rather than general .NET usage

Code Comparison

Roslyn (syntax tree manipulation):

var tree = CSharpSyntaxTree.ParseText("class C { }");
var root = tree.GetRoot();
var newRoot = root.ReplaceNode(
    root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(),
    SyntaxFactory.ClassDeclaration("NewClass")
);

Samples (basic C# usage):

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

Summary

Roslyn is a powerful toolkit for working with C# and VB compilers, offering advanced capabilities for code analysis and manipulation. It's ideal for developers creating language tools or deep .NET integrations. Samples, on the other hand, provides a broad range of .NET code examples, making it more accessible for learners and developers seeking practical implementations across various .NET technologies.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.NET Samples

Markdownlint Snippets 5000 target supported version

This repo contains all the sample code that is part of any topic under the .NET documentation. There are several different projects that are organized in sub-folders. These sub-folders are organized similarly to the organization of the docs for .NET. Some of the articles will have more than one sample associated with them.

The content team tracks issues for .NET documentation in the dotnet/docs and dotnet/dotnet-api-docs repositories. Issues are turned off on this repository. File issues against existing samples and suggestions for new samples in those repositories. If you're not sure where, choose dotnet/docs. This process keeps the issues associated with the articles that explain the concepts for each sample. The best process is to file an issue from the feedback control at the bottom of each docs page:

  • For existing samples, file the issue on the page with the sample.
  • To suggest new samples, file the issue on the index page where you want to see the new sample.

The code in this repository represents programs that demonstrate application or library scenarios. These samples often use more than one technology, feature, or toolkit. Each sample has a readme.md file that explains the sample and links to resources for more information.

Samples should be buildable projects. Those projects should build and run on the widest set of platforms possible for the given sample. In practice, that means building .NET Core-based console applications where possible. Samples that are specific to the web or a UI framework should add those tools as needed. Examples include web applications, mobile apps, WPF or Windows Forms apps, and so on.

We are working toward having a CI system in place for all code. When you make any updates to samples, make sure each update is part of a buildable project. Ideally, add tests for correctness on samples as well.

Building a sample

Build any .NET Core sample using the .NET Core CLI, which is installed with the .NET Core SDK. Then run these commands from the CLI in the directory of any sample:

dotnet build
dotnet run

These will install any needed dependencies, build the project, and run the project respectively.

Multi-project samples have instructions in their root directory in a README.md file.

Except where noted, all samples build from the command line on any platform supported by .NET Core. There are a few samples that are specific to Visual Studio and require Visual Studio 2017 or later. In addition, some samples show platform-specific features and will require a specific platform. Other samples and snippets require the .NET Framework and will run on Windows platforms, and will need the Developer Pack for the target Framework version.

Creating new samples

If you wish to add a code sample:

  1. Your sample must be part of a buildable project. Where possible, the projects should build on all platforms supported by .NET Core. Exceptions to this are samples that demonstrate a platform-specific feature or platform-specific tool.

  2. Your sample should conform to the runtime coding style to maintain consistency.

    • Additionally, we prefer the use of static methods rather than instance methods when demonstrating something that doesn't require instantiating a new object.
  3. Your sample should include appropriate exception handling. It should handle all exceptions that are likely to be thrown in the context of the sample. For example, a sample that calls the Console.ReadLine method to retrieve user input should use appropriate exception handling when the input string is passed as an argument to a method. Similarly, if your sample expects a method call to fail, the resulting exception must be handled. Always handle the specific exceptions thrown by the method, rather than base class exceptions such as Exception or SystemException.

  4. If your sample builds a standalone package, you must include the runtimes used by our CI build system, in addition to any runtimes used by your sample:

    • win7-x64
    • win8-x64
    • win81-x64
    • ubuntu.16.04-x64

We will have a CI system in place to build these projects shortly.

To create a sample:

  1. File an issue or add a comment to an existing one that you are working on it.

  2. Write the topic that explains the concepts demonstrated in your sample (example: docs/standard/linq/where-clause.md).

  3. Write your sample (example: WhereClause-Sample1.cs).

  4. Create a Program.cs with a Main entry point that calls your samples. If there is already one there, add the call to your sample:

    public class Program
    {
        public void Main(string[] args)
        {
            WhereClause1.QuerySyntaxExample();
    
            // Add the method syntax as an example.
            WhereClause1.MethodSyntaxExample();
        }
    }
    
  5. Don't check in the solution file if it contains only one project.

To build and run your sample:

  1. Go to the sample folder and build to check for errors:

    dotnet build
    
  2. Run your sample:

    dotnet run
    
  3. Add a README.md to the root directory of your sample.

    This should include a brief description of the code, and refer people to the article that references the sample.