Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurança

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
012345678901234567890123456789012345678901234567890123456789
Ontem
012345678901234567890123456789012345678901234567890123456789
Visualizações totais
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de C#
C#
Getting Started with CSyntax BasicsTypes and DataProjects and PackagesErrors and TestingKey Concepts: LINQ, Delegates, and Async
Discussões

Guia de C# · 2/6

Syntax Basics

Por enquanto, este capítulo está disponível apenas em inglês.

This chapter covers the everyday building blocks of C#: variables, methods, control flow, string interpolation, and the namespaces that organize your code. If you have written C, Java, or JavaScript, most of the syntax will feel familiar right away.

Variables and Constants

C# is statically typed, so every variable's type is fixed at compile time. You can spell the type out, or use var and let the compiler infer it from the right-hand side. Either way the type is locked in; var is not a dynamic type.

int count = 10;
double price = 19.99;
string title = "Learning C#";
bool isActive = true;

var total = count * price;      // inferred as double
var names = new List<string>(); // inferred as List<string>

const int MaxRetries = 3;       // compile-time constant
count += 5;                     // variables can be reassigned
// MaxRetries = 4;              // error: constants cannot change

By convention, locals and parameters use camelCase, while methods, properties, types, and constants use PascalCase. Statements end with a semicolon.

Methods

A method declaration lists a return type, a name, and parameters; use void when nothing is returned. When the body is a single expression, the => arrow form keeps it short.

static int Add(int a, int b)
{
    return a + b;
}

static int Square(int x) => x * x;

// optional parameter with a default value
static string Greet(string name, string greeting = "Hello")
    => $"{greeting}, {name}!";

Console.WriteLine(Add(2, 3));                         // 5
Console.WriteLine(Square(4));                         // 16
Console.WriteLine(Greet("Sam"));                      // Hello, Sam!
Console.WriteLine(Greet(greeting: "Hi", name: "Jo")); // named arguments

Methods declared in a top-level statements file become local functions inside the generated entry point. Inside a class, a static method belongs to the type itself, while a method without static belongs to each instance. Methods can also hand back extra values through out parameters; int.TryParse is the classic example.

Control Flow

Conditionals and loops look just like other curly-brace languages. On top of that, C# offers switch expressions and pattern matching for compact branching.

int score = 87;

if (score >= 90)
    Console.WriteLine("A");
else if (score >= 80)
    Console.WriteLine("B");
else
    Console.WriteLine("C or below");

string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    _ => "F",
};

for (int i = 0; i < 3; i++)
    Console.WriteLine($"for: {i}");

foreach (var fruit in new[] { "apple", "pear", "plum" })
    Console.WriteLine($"foreach: {fruit}");

int n = 0;
while (n < 3)
{
    n++;
    if (n == 2) continue; // skip to the next iteration
    Console.WriteLine($"while: {n}");
}
Dúvidas sobre este capítulo?
Capítulo anteriorGetting Started with CPróximo capítuloTypes and Data

The _ arm in a switch expression is the catch-all, and the compiler warns you if some inputs are left unhandled. The is operator matches patterns too: if (value is int number && number > 0) checks the type, converts, and tests the value in one go.

String Interpolation

Prefix a string with $ to embed expressions in braces. A format specifier after a colon controls how numbers and dates are rendered.

var item = "Keyboard";
var unitPrice = 49.90m;
var quantity = 2;

Console.WriteLine($"{quantity} x {item}: {unitPrice * quantity:C}");
Console.WriteLine($"Ratio: {0.256:P1}");          // 25.6%
Console.WriteLine($"|{item,-10}|{quantity,5}|");  // left and right alignment

var path = @"C:\data\report.txt";               // verbatim string: backslashes stay as-is
var json = """
    { "name": "TASTEDEV", "ok": true }
    """;                                         // raw string literal

The m suffix makes a decimal, the right type for money. The C format uses the current culture's currency format, so its output depends on the machine. Raw string literals, delimited by three double quotes, need no escaping for quotes or backslashes, which makes them ideal for embedded JSON or SQL.

Namespaces and using Directives

Namespaces group types so their names don't collide. Writing namespace Name; at the top of a file places every type in that file inside the namespace (a file-scoped namespace). To use types from another namespace, import it with a using directive.

// Models/Order.cs
namespace Shop.Models;

public class Order
{
    public int Id { get; set; }
}
// Program.cs
using System.Text;
using Shop.Models;

var order = new Order { Id = 42 };
var builder = new StringBuilder();
builder.Append("Order number: ").Append(order.Id);
Console.WriteLine(builder.ToString());

With ImplicitUsings enabled you never have to write out namespaces like System, System.Collections.Generic, or System.Linq. To make your own import available project-wide, add a line such as global using Shop.Models; to any one file.

Summary

  • Declare variables with an explicit type or var; either way, the type is fixed at compile time.
  • Methods have a return type, name, and parameters; short bodies use =>, and callers can use optional and named arguments.
  • Beyond if, for, foreach, and while, switch expressions and pattern matching keep branching concise.
  • $"..." interpolation with format specifiers shapes output, and raw string literals hold multi-line text verbatim.
  • File-scoped namespaces group your types, and using brings in types from other namespaces.

0 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.