Documentation
Languages and Frameworks/C#

C# Support

ThinkCode provides robust support for C# development, offering specialized tools, intelligent code assistance, and advanced features designed to enhance productivity when working with C# and .NET technologies.

Getting Started

Setup and Configuration

ThinkCode automatically detects C# projects. For optimal experience:

  1. Install C# Extension:

    • ThinkCode will prompt to install the C# extension when you open a C# file
    • Alternatively, open the Extensions view (Ctrl+Shift+X / Cmd+Shift+X) and search for "ThinkCode C#"
  2. Install .NET SDK:

    • Ensure .NET SDK is installed on your system
    • ThinkCode will detect the .NET installation automatically
    • Configure .NET version in settings if needed
  3. Project Configuration:

    • ThinkCode supports standard .NET project structures
    • Automatically recognizes .csproj and .sln files
    • Configures the C# environment variables
  4. Create a New Project:

    • Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
    • Type "ThinkCode: Create New Project"
    • Select C# from template categories
    • Choose from templates:
      • Console Application
      • Class Library
      • ASP.NET Core Web App/API
      • WPF Application
      • Blazor Application
      • Xamarin/MAUI Project

IntelliSense and Code Navigation

Code Intelligence

ThinkCode provides advanced intelligence for C#:

  • Auto-Completion: Context-aware suggestions for:

    • Classes and members
    • Method overloads
    • LINQ queries
    • NuGet packages
  • Type Information: Detailed type information with tooltips

  • Signature Help: Parameter info for methods and constructors

  • Quick Documentation: Access XML documentation directly in the editor

Example of C# code with intelligent assistance:

// ThinkCode provides intelligent assistance for C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
namespace MyApplication
{
    // ThinkCode offers XML documentation generation
    /// <summary>
    /// Represents a product in the e-commerce system
    /// </summary>
    public class Product
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public int StockQuantity { get; set; }
        public DateTime CreatedAt { get; set; }
        public List<string> Categories { get; set; } = new List<string>();
 
        // ThinkCode provides constructor suggestions
        public Product(string name, decimal price)
        {
            Id = Guid.NewGuid();
            Name = name;
            Price = price;
            CreatedAt = DateTime.UtcNow;
        }
 
        // ThinkCode offers method completion
        public bool IsInStock()
        {
            return StockQuantity > 0;
        }
 
        // ThinkCode understands C# expression syntax
        public decimal GetDiscountedPrice(decimal discountPercentage) =>
            Price - (Price * discountPercentage / 100);
    }
 
    public class ProductService
    {
        private readonly List<Product> _products = new List<Product>();
 
        // ThinkCode provides intelligent LINQ suggestions
        public List<Product> GetProductsByCategory(string category)
        {
            return _products
                .Where(p => p.Categories.Contains(category))
                .OrderBy(p => p.Name)
                .ToList();
        }
 
        // ThinkCode understands async/await patterns
        public async Task<Product> GetProductByIdAsync(Guid id)
        {
            // Simulate database access
            await Task.Delay(100);
 
            return _products.FirstOrDefault(p => p.Id == id);
        }
    }
}

Smart Navigation

Navigate your codebase efficiently:

  • Go to Definition: Jump to declarations

    • Keyboard: F12 or Ctrl+Click / Cmd+Click
    • Works across projects and references
  • Find All References: Locate all usages of a symbol

    • Keyboard: Shift+F12
    • Results organized by file and location
  • Go to Implementation: Jump to implementations of interfaces

    • Keyboard: Ctrl+F12 / Cmd+F12
  • Outline View: Explore the structure of C# files

    • Keyboard: Ctrl+Shift+O / Cmd+Shift+O
    • Shows namespaces, classes, methods, and properties
  • Solution Explorer: Navigate through solution structure

    • Keyboard: Ctrl+Alt+L / Cmd+Option+L

Namespace and Using Management

Efficient handling of C# namespaces:

  • Auto-Using: Automatically add missing using directives
  • Organize Usings: Remove unused directives and organize
  • Using Completion: Intelligent namespace suggestions
  • Reference Management: Add and manage project references

Configure import behavior:

{
  "thinkcode.csharp.namespaces": {
    "autoOrganize": true,
    "placeSystemFirst": true,
    "addMissingUsings": true,
    "highlightUnused": true
  }
}

AI-Powered Development Features

Smart Code Generation

Generate C# code with natural language prompts:

  1. Method Generation:

    • Add a comment describing method purpose
    • Press Alt+I / Option+I for AI implementation

    Example:

    // Generate a method that validates an email address using regex
    // Press Alt+I here and ThinkCode generates the implementation
    public bool IsValidEmail(string email)
    {
        if (string.IsNullOrWhiteSpace(email))
            return false;
     
        try
        {
            // Use System.Net.Mail for validation
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
     
        // Alternative using regex
        // var regex = new Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase);
        // return regex.IsMatch(email);
    }
  2. Class Generation:

    • Describe class purpose in a comment
    • ThinkCode generates a complete class with properties and methods
  3. Test Generation:

    • Select method to test
    • Right-click and select "Generate Unit Tests"
    • ThinkCode generates xUnit, NUnit, or MSTest tests

Code Refactoring

AI-assisted refactoring capabilities:

  • Extract Method: Create a new method from selected code
  • Rename Symbol: Intelligently rename variables, methods, and types
  • Introduce Variable: Create a variable from an expression
  • Encapsulate Field: Convert field to property
  • Generate Constructor: Create constructor from fields/properties

Access refactoring tools:

  1. Right-click in editor
  2. Select "Refactor" menu
  3. Choose desired refactoring operation

Documentation Assistant

Generate and maintain C# documentation:

  • XML Comment Generation: Auto-generate XML documentation
  • README Creation: Generate project documentation
  • API Documentation: Create API reference documentation
  • Examples: Generate example usage code

Example of AI-assisted documentation:

// Place cursor here and use Command Palette > "Generate Documentation"
/// <summary>
/// Processes a collection of items using the specified filter and transformation.
/// </summary>
/// <typeparam name="TInput">The type of the input items.</typeparam>
/// <typeparam name="TOutput">The type of the output items.</typeparam>
/// <param name="items">The collection of items to process.</param>
/// <param name="filter">A predicate function that determines whether an item should be processed.</param>
/// <param name="transform">A function that transforms an input item to an output item.</param>
/// <param name="parallel">If true, processing will be performed in parallel.</param>
/// <returns>
/// A collection of transformed items that passed the filter criteria.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="items"/>, <paramref name="filter"/>, or <paramref name="transform"/> is null.
/// </exception>
/// <remarks>
/// If <paramref name="parallel"/> is true, the method will use PLINQ for processing,
/// which may improve performance for large collections or expensive transformations.
/// </remarks>
/// <example>
/// <code>
/// var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
/// var evenSquares = ProcessItems(
///     numbers,
///     n => n % 2 == 0,      // Filter: only even numbers
///     n => n * n,           // Transform: square the number
///     true                  // Process in parallel
/// );
/// // evenSquares contains: 4, 16, 36, 64, 100
/// </code>
/// </example>
public static IEnumerable<TOutput> ProcessItems<TInput, TOutput>(
    IEnumerable<TInput> items,
    Func<TInput, bool> filter,
    Func<TInput, TOutput> transform,
    bool parallel)
{
    // Implementation...
}

Project Management

Solution Management

Efficiently manage .NET solutions:

  • Solution Explorer: Navigate multi-project solutions
  • Project References: Manage project dependencies
  • Build Configurations: Switch between Debug and Release
  • Target Frameworks: Configure target .NET versions

Access solution explorer:

  1. View menu
  2. Select "Solution Explorer"
  3. Navigate projects and files

NuGet Package Management

Seamless package management:

  • Package Search: Find and add NuGet packages
  • Version Management: Update package versions
  • Dependency Visualization: View package dependencies
  • Local Feeds: Configure private NuGet sources

Access NuGet tools:

  1. Right-click on project
  2. Select "Manage NuGet Packages"
  3. Search and install packages

Debugging and Testing

Debugging

Powerful C# debugging capabilities:

  • Integrated Debugger: Debug .NET applications directly
  • Breakpoints:
    • Conditional breakpoints
    • Hit count breakpoints
    • Logpoints (print without stopping)
  • Data Inspection: Examine variables and complex objects
  • Expression Evaluation: Evaluate C# expressions while debugging

Example launch configuration:

// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch .NET Core Console",
      "type": "thinkcode-csharp",
      "request": "launch",
      "program": "${workspaceFolder}/bin/Debug/net7.0/MyApp.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "console": "internalConsole"
    },
    {
      "name": "Launch ASP.NET Core",
      "type": "thinkcode-csharp",
      "request": "launch",
      "program": "${workspaceFolder}/bin/Debug/net7.0/MyWebApp.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "serverReadyAction": {
        "action": "openExternally",
        "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
      }
    }
  ]
}

Testing

Integrated support for .NET testing:

  • Test Explorer: View and run tests with visual UI
  • Test Discovery: Automatically find tests in your project
  • Live Testing: Run tests as you type
  • Coverage Visualization: See code coverage in editor

Supported test frameworks:

  • xUnit
  • NUnit
  • MSTest

Run tests with:

  1. Click on test gutter icons
  2. Right-click on test method
  3. Use Test Explorer view

Code Quality and Analysis

Linting and Static Analysis

Integrated code quality tools:

  • Roslyn Analyzers: Detect code issues and style violations
  • Code Fixes: Apply suggested fixes automatically
  • Style Rule Configuration: Configure code style rules
  • Error Lens: See errors and warnings inline

Configure analyzers:

{
  "thinkcode.csharp.analysis": {
    "enabled": true,
    "diagnosticLevel": "warning", // Options: "info", "warning", "error"
    "analyzers": {
      "styleAnalyzers": true,
      "qualityAnalyzers": true,
      "securityAnalyzers": true
    },
    "rulesets": ["default", "security", "performance"]
  }
}

Code Formatting

Maintain consistent code style:

  • Format Document: Apply formatting rules
  • Format Selection: Format selected code
  • Format on Save: Automatically format while saving
  • EditorConfig Support: Use EditorConfig for style rules

Example .editorconfig configuration:

# EditorConfig is supported by ThinkCode
root = true

[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true

[*.cs]
indent_style = space
indent_size = 4

# C# formatting rules
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_space_after_keywords_in_control_flow_statements = true
csharp_indent_case_contents = true

# Use var when the type is apparent
csharp_style_var_for_built_in_types = false:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = false:suggestion

# Expression-bodied members
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_accessors = true:suggestion

ASP.NET Core Development

Web App Development

Specialized tools for ASP.NET Core web development:

  • Project Templates: Create MVC, Razor Pages, and Blazor projects
  • View Navigation: Jump between controllers and views
  • Razor Intelligence: Smart completion in Razor files
  • Tag Helper Support: Intelligent tag helper completion

API Development

Tools for building RESTful APIs:

  • Controller Generation: Generate API controllers
  • Swagger Integration: Visualize and test APIs
  • API Documentation: Generate OpenAPI documentation
  • HTTP Client: Test API endpoints

Example of ASP.NET Core controller with intelligent assistance:

// ThinkCode provides intelligent assistance for ASP.NET Core
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using MyApp.Models;
using MyApp.Services;
 
namespace MyApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductsController : ControllerBase
    {
        private readonly IProductService _productService;
 
        // ThinkCode offers dependency injection completion
        public ProductsController(IProductService productService)
        {
            _productService = productService;
        }
 
        // ThinkCode provides route and status code suggestions
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
        {
            var products = await _productService.GetAllProductsAsync();
            return Ok(products);
        }
 
        [HttpGet("{id}")]
        public async Task<ActionResult<Product>> GetProduct(string id)
        {
            var product = await _productService.GetProductByIdAsync(id);
 
            if (product == null)
                return NotFound();
 
            return Ok(product);
        }
 
        [HttpPost]
        public async Task<ActionResult<Product>> CreateProduct(ProductCreateDto dto)
        {
            // ThinkCode understands model validation
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
 
            var product = await _productService.CreateProductAsync(dto);
 
            // ThinkCode knows RESTful URL generation
            return CreatedAtAction(
                nameof(GetProduct),
                new { id = product.Id },
                product
            );
        }
 
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateProduct(string id, ProductUpdateDto dto)
        {
            if (id != dto.Id)
                return BadRequest();
 
            var success = await _productService.UpdateProductAsync(dto);
 
            if (!success)
                return NotFound();
 
            return NoContent();
        }
 
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProduct(string id)
        {
            var success = await _productService.DeleteProductAsync(id);
 
            if (!success)
                return NotFound();
 
            return NoContent();
        }
    }
}

Blazor Support

Specialized tooling for Blazor development:

  • Component Intelligence: Smart completion in components
  • Event Binding: Auto-completion for event handlers
  • Component Navigation: Jump between components
  • State Management: Visualization of component state

Example of Blazor component with intelligent assistance:

@page "/products/{id}"
@using MyApp.Models
@using MyApp.Services
@inject IProductService ProductService
@inject NavigationManager NavigationManager
 
<h1>Product Details</h1>
 
@if (loading)
{
    <div class="loading-spinner">
        <div class="spinner-border" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>
}
else if (product == null)
{
    <div class="alert alert-warning">
        Product not found.
    </div>
}
else
{
    <div class="card">
        <div class="card-header">
            <h2>@product.Name</h2>
        </div>
        <div class="card-body">
            <p class="card-text">@product.Description</p>
            <p class="price">Price: $@product.Price.ToString("F2")</p>
 
            @if (product.IsInStock())
            {
                <p class="stock in-stock">In Stock (@product.StockQuantity available)</p>
                <button class="btn btn-primary" @onclick="AddToCart">Add to Cart</button>
            }
            else
            {
                <p class="stock out-of-stock">Out of Stock</p>
                <button class="btn btn-secondary" disabled>Add to Cart</button>
            }
        </div>
    </div>
 
    <div class="mt-3">
        <button class="btn btn-outline-primary" @onclick="GoBack">Back to Products</button>
    </div>
}
 
@code {
    [Parameter]
    public string Id { get; set; }
 
    private Product product;
    private bool loading = true;
 
    // ThinkCode understands Blazor lifecycle methods
    protected override async Task OnInitializedAsync()
    {
        try
        {
            loading = true;
            product = await ProductService.GetProductByIdAsync(Id);
        }
        finally
        {
            loading = false;
        }
    }
 
    private async Task AddToCart()
    {
        await ProductService.AddToCartAsync(product.Id);
        // Show toast notification
        await JSRuntime.InvokeVoidAsync("showToast", "Product added to cart!");
    }
 
    private void GoBack()
    {
        NavigationManager.NavigateTo("/products");
    }
}

Desktop Application Development

WPF Support

Tools for Windows Presentation Foundation:

  • XAML Support: Intelligent XAML editing
  • Data Binding: Smart completion for bindings
  • Resource Dictionary: Navigation and completion
  • MVVM Pattern: Tools for implementing MVVM

Windows Forms

Support for Windows Forms applications:

  • Designer Integration: Visual designer for forms
  • Control Properties: Smart property editing
  • Event Handlers: Auto-generate event handlers
  • Data Binding: Support for data-bound controls

MAUI Development

Tools for .NET MAUI cross-platform applications:

  • XAML Intelligence: Smart editing for MAUI XAML
  • Device Preview: Preview on different platforms
  • Platform-Specific Code: Assistance for platform conditionals
  • Resources Management: Handle application resources

.NET Performance Tools

Performance Analysis

Identify and optimize .NET performance:

  • Performance Profiler: Find performance bottlenecks
  • Memory Profiler: Track allocations and GC behavior
  • Benchmark.NET Integration: Run and analyze benchmarks
  • Database Query Analysis: Optimize Entity Framework queries

Access performance tools:

  1. Command Palette
  2. Type "ThinkCode: Profile .NET Application"
  3. Select profiling type

Example Benchmark.NET integration:

// ThinkCode provides intelligent performance analysis
[Benchmark]
public void SortSmallArray()
{
    var array = new[] { 5, 3, 1, 8, 2, 4, 7, 6 };
    Array.Sort(array);
    // ThinkCode shows performance metrics and suggestions
}

Optimization Suggestions

Get intelligent suggestions for improving performance:

  • Algorithmic Improvements: More efficient implementations
  • Memory Usage: Reduce allocations and GC pressure
  • Parallel Processing: Identify parallelization opportunities
  • Caching Strategies: Implement appropriate caching

.NET Ecosystem Integration

Entity Framework Core

Advanced support for EF Core:

  • DbContext Intelligence: Smart completion for context configuration
  • Migration Management: Create and apply migrations
  • Query Syntax: Assistance for LINQ queries
  • Model Visualization: View entity relationships

Example of EF Core with intelligent assistance:

// ThinkCode provides intelligent assistance for Entity Framework Core
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
 
namespace MyApp.Data
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
        public List<OrderItem> OrderItems { get; set; }
    }
 
    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Product> Products { get; set; }
    }
 
    public class Order
    {
        public int Id { get; set; }
        public DateTime OrderDate { get; set; }
        public string CustomerId { get; set; }
        public List<OrderItem> Items { get; set; }
    }
 
    public class OrderItem
    {
        public int Id { get; set; }
        public int OrderId { get; set; }
        public Order Order { get; set; }
        public int ProductId { get; set; }
        public Product Product { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
    }
 
    // ThinkCode provides DbContext configuration suggestions
    public class AppDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderItem> OrderItems { get; set; }
 
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }
 
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // ThinkCode offers Entity Framework fluent API suggestions
            modelBuilder.Entity<Product>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
                entity.Property(e => e.Price).HasColumnType("decimal(18,2)");
 
                entity.HasOne(e => e.Category)
                      .WithMany(c => c.Products)
                      .HasForeignKey(e => e.CategoryId)
                      .OnDelete(DeleteBehavior.Restrict);
            });
 
            modelBuilder.Entity<OrderItem>(entity =>
            {
                entity.HasKey(e => e.Id);
 
                entity.HasOne(e => e.Order)
                      .WithMany(o => o.Items)
                      .HasForeignKey(e => e.OrderId);
 
                entity.HasOne(e => e.Product)
                      .WithMany(p => p.OrderItems)
                      .HasForeignKey(e => e.ProductId);
 
                entity.Property(e => e.UnitPrice).HasColumnType("decimal(18,2)");
            });
        }
    }
}

.NET Core Integration

Support for .NET Core command-line tools:

  • dotnet CLI Integration: Run dotnet commands
  • Project Templates: Create from templates
  • Tool Management: Install and manage .NET tools
  • Configuration: Edit .NET Core configuration

Customization

Extension Points

Extend ThinkCode's C# support:

  • Custom Analyzers: Create specialized Roslyn analyzers
  • Code Generators: Implement custom code generators
  • Project Templates: Define custom project templates
  • Build Tasks: Configure custom build workflows

Configuration Options

Comprehensive configuration for C# development:

{
  "thinkcode.csharp": {
    "format": {
      "enable": true,
      "onSave": true,
      "enableEditorconfig": true
    },
    "analysis": {
      "enabled": true,
      "rulesetLocation": "${workspaceFolder}/.ruleset",
      "excludePatterns": ["**/bin/**", "**/obj/**"]
    },
    "completion": {
      "showItemsFromUnimportedNamespaces": true,
      "addImportOnCompletion": true
    },
    "navigation": {
      "definitionProvider": true,
      "implementationProvider": true,
      "referencesProvider": true
    },
    "testing": {
      "enabled": true,
      "useLegacyRunner": false,
      "autoDiscoverAfterBuild": true,
      "framework": "auto"  // Options: "auto", "xunit", "nunit", "mstest"
    },
    "dotnet": {
      "cliPath": "dotnet",
      "runtimePath": null,
      "includePrerelease": false
    }
  }
}

Resources and Learning

Learning Paths

Integrated learning resources:

  • C# Tutorials: Learn C# concepts
  • Framework Guides: .NET-specific learning paths
  • Interactive Challenges: Practice with coding exercises
  • Sample Projects: Explore and learn from example projects

Access learning resources:

  1. Command Palette
  2. Type "ThinkCode: Open Learning Hub"
  3. Select C# category

Community Integration

Connect with the .NET community:

  • Documentation: Access .NET documentation inline
  • Stack Overflow: Search solutions directly from ThinkCode
  • GitHub: Find example implementations
  • NuGet Gallery: Discover packages

Additional .NET Development Scenarios

Microservices Architecture

Support for microservice development:

  • Service Templates: Standard microservice layouts
  • Docker Integration: Containerize .NET applications
  • Kubernetes Support: Deploy to Kubernetes clusters
  • Service Fabric: Integration with Azure Service Fabric

Serverless Applications

Tools for serverless development:

  • Azure Functions: Create and deploy functions
  • AWS Lambda: Build .NET Lambda functions
  • Local Debugging: Test functions locally
  • Configuration Management: Manage environment settings

Cloud Integration

Support for cloud service integration:

  • Azure DevOps: CI/CD pipeline integration
  • Azure Services: Connect to Azure resources
  • AWS Integration: Work with AWS services
  • GCP Support: Integrate with Google Cloud

Further Information