Basic Syntax C Sharp Language

Basic Syntax in C# Language

C# is a versatile and widely-used programming language developed by Microsoft. It is known for its simplicit

y and power, making it a popular choice for developing a wide range of applications, including desktop software, web applications, games, and more. In this post, we will explore the basic syntax of the C# language, providing you with a foundation to start writing your own C# programs.

Hello, World!

Let’s start with the traditional “Hello, World!” program to get a feel for the basic syntax of C#. In C#, this program is written as follows:

using System;

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

Here’s a breakdown of what’s happening in this code:

  • using System;: This line is used to import the System namespace, which contains the Console class. Namespaces are used to organize classes and types in C#.
  • class Program: This declares a class named Program, which is the entry point of the application.
  • static void Main(): This is the entry point of the C# program. It’s a special method that’s executed when the program is run. static means the method is associated with the class itself, and void indicates that it doesn’t return any value.
  • Console.WriteLine("Hello, World!");: This line uses the Console.WriteLine method to display the text “Hello, World!” in the console.

Data Types

C# supports various data types, including:

  • int: Used to store integer values.
  • double: Used to store floating-point numbers.
  • bool: Used to store true or false values.
  • string: Used to store text.

Here’s an example of declaring and initializing variables:

int age = 25;
double price = 19.99;
bool isCSharpFun = true;
string greeting = "Hello, C#!";

Control Structures

C# offers several control structures for making decisions and repeating actions. Some of the most common ones include:

Conditional Statements (if-else)

int score = 85;
if (score >= 90)
{
    Console.WriteLine("A Grade");
}
else if (score >= 80)
{
    Console.WriteLine("B Grade");
}
else
{
    Console.WriteLine("C Grade");
}

Loops (for and while)

  • For Loop
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine("Iteration " + i);
}
  • While Loop
int counter = 1;
while (counter <= 5)
{
    Console.WriteLine("Iteration " + counter);
    counter++;
}

Functions (Methods)

C# allows you to define your own methods for organizing and reusing code. Here’s an example of a simple method:

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

You can call this method as follows:

int result = Add(3, 4);
Console.WriteLine("The result is: " + result);

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading