C# Syntax
Learn the rules and structure of C# code
π C# Syntax Basics
C# syntax defines the rules for writing valid code. Understanding syntax helps you write programs that compile and run correctly without errors.
using System;
class SyntaxExample
{
static void Main()
{
Console.WriteLine("Learning C# Syntax!");
}
}
Output:
Learning C# Syntax!
Syntax Rules
Semicolons
Every statement ends with a semicolon
int x = 5;
Console.WriteLine(x);
Curly Braces
Define code blocks and scope
if (true)
{
// Code here
}
Case Sensitive
Uppercase and lowercase matter
int Age = 25;
int age = 30;
// Different!
Namespaces
Organize code into logical groups
using System;
using System.Linq;
πΉ Basic Program Structure
Every C# program follows a fundamental structure: using directives for namespaces, a class definition containing code, and the Main method as the entry point. The skeleton looks like: using System; class Program { static void Main() { Console.WriteLine("Hello!"); } }. This structure ensures proper code organization, modularity, and execution flow. Understanding this foundation is crucial for beginners, as it introduces key concepts like classes, methods, and the common language runtime. Itβs the starting point for all console applications, laying the groundwork for more complex architectures.
using System; // 1. Import namespaces
namespace MyProgram // 2. Define namespace (optional)
{
class Program // 3. Define class
{
static void Main(string[] args) // 4. Main method
{
// 5. Your code here
Console.WriteLine("Hello!");
}
}
}
Output:
Hello!
πΉ Statements and Expressions
C# statements and expressions are fundamental to writing executable code.
A statement is a complete instruction that performs an action, like declaring a variable or calling a method, and it must end with a semicolon. An expression, on the other hand, is a piece of code that produces a value, such as 5 + 3 or x * 2. This value can then be used within a statement. Understanding the difference is key to controlling how your program flows and manipulates data.
using System;
class Statements
{
static void Main()
{
// Variable declaration statement
int number = 10;
// Expression statement
int result = number + 5;
// Method call statement
Console.WriteLine(result);
// Assignment statement
number = 20;
Console.WriteLine(number);
}
}
Output:
15
20
πΉ Code Blocks
Code blocks in C# group multiple statements together using curly braces {}. This grouping is essential for defining the scope of variables and controlling the structure of your program. Variables declared inside a block are only accessible within that block, a concept known as block scope. This encapsulation helps prevent naming conflicts and manages memory efficiently, making your code more organized, secure, and easier to debug. Blocks are used in methods, loops, and conditional statements.
using System;
class CodeBlocks
{
static void Main()
{
// Outer block
int x = 10;
{
// Inner block
int y = 20;
Console.WriteLine("x: " + x); // Can access x
Console.WriteLine("y: " + y); // Can access y
}
Console.WriteLine("x: " + x); // Can access x
// Console.WriteLine(y); // ERROR: y not accessible here
}
}
Output:
x: 10
y: 20
x: 10
πΉ Naming Conventions
C# follows specific naming rules and conventions. Following these makes your code readable and professional.
Rules (Must Follow):
- Names can contain letters, digits, and underscores
- Must start with a letter or underscore
- Cannot use C# keywords (like int, class, if)
- Case sensitive (age and Age are different)
Conventions (Should Follow):
- Classes: PascalCase (MyClass, StudentRecord)
- Methods: PascalCase (GetName, CalculateTotal)
- Variables: camelCase (firstName, totalAmount)
- Constants: PascalCase (MaxValue, DefaultSize)
using System;
class NamingExample
{
static void Main()
{
// Good variable names
string firstName = "John";
int studentAge = 20;
double accountBalance = 1000.50;
// Good constant
const int MaxAttempts = 3;
Console.WriteLine(firstName);
Console.WriteLine("Age: " + studentAge);
Console.WriteLine("Balance: $" + accountBalance);
}
}
Output:
Adhering to C# naming conventions is crucial for writing professional, readable, and maintainable code. It involves using PascalCase for class and method names (e.g., CalculateTotal), and camelCase for local variables and parameters (e.g., userAge). Descriptive names are preferred over abbreviations. Following these established guidelines not only makes your code self-documenting for other developers but also ensures consistency with the wider .NET ecosystem and frameworks, improving collaboration and long-term project health.
πΉ Whitespace and Indentation
Proper whitespace and indentation are vital for code readability, even though C# compilers ignore extra spaces. Consistent indentation, typically using tabs or four spaces, visually represents the structure of your code, making it clear where code blocks, methods, and loops begin and end. This practice is not just about aesthetics; it significantly reduces errors, simplifies debugging, and is a cornerstone of professional coding standards that every developer should adopt to improve code clarity and team collaboration.
πΈ Bad Formatting:
using System;
class Bad{static void Main(){int x=5;if(x>0){Console.WriteLine("Positive");}}}
πΈ Good Formatting:
using System;
class Good
{
static void Main()
{
int x = 5;
if (x > 0)
{
Console.WriteLine("Positive");
}
}
}
Output (Both):
Positive
πΉ Keywords
C# keywords are reserved words with predefined meanings that are integral to the language's syntax. Examples include int, if, for, class, and public. You cannot use these words as names for variables, methods, or classes. They form the basic building blocks for defining data types, controlling program flow, modifying declarations, and handling exceptions. Attempting to use a keyword as an identifier will result in a compilation error, so it's essential to familiarize yourself with the complete list of C# reserved keywords.
Common Keywords:
using System;
class Keywords
{
static void Main()
{
// Using keywords correctly
int number = 10; // 'int' is a keyword
string text = "Hello"; // 'string' is a keyword
if (number > 5) // 'if' is a keyword
{
Console.WriteLine(text);
}
}
}