Expanded_Basic_Functions_of_CSharp
Expanded_Basic_Functions_of_CSharp
Introduction
C# (pronounced C-Sharp) is a modern, object-oriented programming language developed
by Microsoft. It is widely used for developing desktop applications, web applications, and
games. Below are some basic functions of C# along with examples.
1. Hello World
The 'Hello World' program is the simplest program in C#. It demonstrates the basic
structure of a C# application.
Example:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
Example:
3. Conditional Statements
Conditional statements allow you to execute certain blocks of code based on conditions.
Example:
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is negative.");
}
4. Loops
Loops allow you to execute a block of code multiple times.
5. Functions
Functions (or methods) are blocks of code that perform a specific task.
Example:
Console.WriteLine(AddNumbers(3, 5));
6. Arrays
Arrays store multiple values of the same type in a single variable.
Example:
int[] numbers = {1, 2, 3, 4, 5};
Example:
class Person
{
public string Name;
public int Age;
8. Inheritance
Inheritance allows a class to inherit methods and properties from another class.
Example:
class Animal
{
public void Eat()
{
Console.WriteLine("This animal eats food.");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("The dog barks.");
}
}
9. Exception Handling
Exception handling helps manage runtime errors in a program.
Example:
try
{
int number = int.Parse("NotANumber");
}
catch (FormatException)
{
Console.WriteLine("Input string is not a valid number.");
}
Example:
using System.IO;
Comprehensive Example
This example combines multiple basic functions in a single program:
using System;
using System.IO;
class Animal
{
public string Name;
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
class Program
{
static void Main()
{
Dog myDog = new Dog();
myDog.Name = "Buddy";
myDog.Eat();
myDog.Bark();
try
{
int result = 10 / 0;
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot divide by zero!");
}