YouTip LogoYouTip

Csharp Basic Syntax

# C# Basic Syntax C# is an object-oriented programming language. In object-oriented programming methods, programs are composed of various interacting objects. Objects of the same kind usually have the same type, or, in other words, are in the same class. For example, take a Rectangle object as an example. It has length and width properties. By design, it may need to accept these property values, calculate the area, and display details. Let's look at an implementation of a Rectangle class and use it to discuss the basic syntax of C#: ## Example using System; namespace RectangleApplication { class Rectangle { // Member variables double length; double width; public void Acceptdetails() { length =4.5; width =3.5; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r =new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } } [Try it Β»](#) When the above code is compiled and executed, it produces the following result: Length: 4.5Width: 3.5Area: 15.75 ## The _using_ Keyword The first statement in any C# program is: using System; The **using** keyword is used to include a namespace in the program. A program can include multiple using statements. ## The _class_ Keyword The **class** keyword is used to declare a class. ## Comments in C# Comments are used to explain code. The compiler ignores comment entries. In C# programs, multi-line comments start with /* and end with the characters */, as shown below: /* This program demonstrates C# comments usage */ Single-line comments are indicated by the // symbol. For example: // This line is a comment ## Member Variables Variables are attributes or data members of a class that are used to store data. In the above program, the _Rectangle_ class has two member variables named _length_ and _width_. ## Member Functions Functions are a series of statements that perform a specified task. Member functions of a class are declared inside the class. Our example class Rectangle contains three member functions: _AcceptDetails_, _GetArea_, and _Display_. ## Instantiating a Class In the above program, the class _ExecuteRectangle_ is a class that contains the _Main()_ method and instantiates the _Rectangle_ class. ## Identifiers Identifiers are used to identify classes, variables, functions, or any other user-defined items. In C#, the naming of a class must follow these basic rules: * An identifier must start with a letter, underscore, or @, followed by a series of letters, digits (0-9), underscores (_), or @. * The first character of an identifier cannot be a digit. * An identifier must not contain any embedded spaces or symbols, such as ? - +! # % ^ & * ( ) { } . ; : " ' / . * An identifier cannot be a C# keyword unless it has an @ prefix. For example, @if is a valid identifier, but if is not, because if is a keyword. * Identifiers must be case-sensitive. Uppercase and lowercase letters are considered different letters. * It cannot have the same name as a C# class library name. ## C# Keywords Keywords are predefined reserved words by the C# compiler. These keywords cannot be used as identifiers, but if you want to use these keywords as identifiers, you can prefix them with the @ character. In C#, some keywords have special meaning in the context of code, such as get and set, which are called contextual keywords. The following table lists the Reserved Keywords and Contextual Keywords in C#: **Reserved Keywords** abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in in (generic modifier)int interface internal is lock long namespace new null object operator out out (generic modifier)override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while **Contextual Keywords** add alias ascending descending dynamic from get global group into join let orderby partial (type) partial (method)remove select set ## Top-Level Statements In C# version 9.0, the concept of Top-Level Statements was introduced. This is a new programming paradigm that allows developers to write statements directly at the top level of a file without encapsulating them in methods or classes. **Features:** * **No Class or Method Required**: Top-level statements allow you to write code directly at the top level of a file without defining a class or method. * **File as Entry Point**: A file containing top-level statements is considered the entry point of the program, similar to the `Main` method in previous C#. * **Automatic `Main` Method**: The compiler automatically generates a `Main` method and uses the top-level statements as the body of the `Main` method. * **Support for Local Functions**: Although no class definition is needed, local functions can still be defined in a file with top-level statements. * **Better Readability**: For simple scripts or tools, top-level statements provide better readability and conciseness. * **Suitable for Small Projects**: Top-level statements are ideal for small projects or scripts, allowing for quick code writing and execution. * **Compatible with Existing Code**: Top-level statements can be used alongside existing C# codebases without affecting the existing code. **Traditional C# Code** - Before using top-level statements, you had to write a C# program like this: ## Example using System; namespace MyApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } } **C# Code with Top-Level Statements** - Using top-level statements, it can be simplified to: ## Example using System; Console.WriteLine("Hello, World!"); Top-level statements support all common C# syntax, including variable declarations, method definitions, exception handling, etc. ## Example using System; using System.Linq; // Variable declaration in top-level statements int number =42; string message ="The answer to life, the universe, and everything is"; // Output variables Console.WriteLine($"{message} {number}."); // Define and call methods int Add(int a, int b)=> a + b; Console.WriteLine($"Sum of 1 and 2 is {Add(1, 2)}."); // Use LINQ var numbers =new[]{1, 2, 3, 4, 5}; var evens = numbers.Where(n => n %2==0).ToArray(); Console.WriteLine("Even numbers: "+string.Join(", ", evens)); // Exception handling try { int zero =0; int result = number / zero; } catch(DivideByZeroException ex) { Console.WriteLine("Error: "+ ex.Message); } ### Notes * **File Limitation:** Top-level statements can only be used in a single source file. If multiple files in a project use top-level statements, it will cause a compilation error. * **Program Entry:** If top-level statements are used, the file will implicitly contain a Main method, and that file will become the entry point of the program. * **Scope Limitation:** Code in top-level statements shares a global scope, meaning variables and methods defined in top-level statements can be accessed throughout the file. Top-level statements have significant advantages in simplifying code structure, reducing learning difficulty, and speeding up development, making them particularly suitable for writing simple programs and scripts.
← Csharp Data TypesCsharp Program Structure β†’