A simple C# program demonstrates the basic structure of C# code, including the ‘Main’ method, which serves as the entry point for execution.
Example:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, C# World!");
}
}
Using System:
‘using System;’ is used to include the ‘System’ namespace, providing access to essential classes and methods like ‘Console’ for input/output operations.
Example:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, C# World!");
}
}
Using Public Modifier:
The ‘public’ modifier is used to make a class, method, or variable accessible from any part of the program. It's essential for creating reusable and accessible code components.
Example:
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
int result = calculator.Add(5, 3);
Console.WriteLine("Result: " + result);
}
}
Using Namespace:
Namespaces are used to organize code into logical groups. By declaring your own namespace, you can encapsulate and structure your code for better maintainability.
Example:
namespace MyApplication
{
class Program
{
static void Main()
{
Console.WriteLine("Inside MyApplication namespace.");
}
}
}
namespace AnotherNamespace
{
class Program
{
static void Main()
{
Console.WriteLine("Inside AnotherNamespace namespace.");
}
}
}