Getting Started with C#

C# is a powerful, modern programming language ideal for building applications ranging from simple utilities to complex systems. In this blog, we’ll explore key aspects of programming in C#, from basic concepts to writing and running your first application.

Programming involves writing a sequence of instructions for computers. These instructions, collectively known as software, can be broadly classified into:

  • System Software: Controls and manages computer hardware (e.g., Windows, macOS, Linux).
  • Application Software: Helps users accomplish specific tasks like document editing, payroll processing, or gaming.

Your code written in high-level languages like C# is called source code. A compiler translates this source code into machine-readable instructions (machine code), allowing the computer to execute your commands efficiently.

Understanding the differences between procedural programming and object-oriented programming is key to choosing the best approach for your project.

Procedural Programming

Procedural programming involves writing sequences of instructions or procedures that the computer follows step-by-step. Each procedure performs a specific task and can be reused throughout the program. In procedural languages (e.g., C, Pascal), data and procedures are separate entities, and functions typically operate independently from the data they manipulate.

Characteristics of Procedural Programming:

  • Separate data and behavior: Data is passed explicitly to procedures.
  • Sequential execution: Statements run in a linear, predictable order.
  • Procedure-oriented: Programs are divided into small functions or procedures.

Example:

// Procedural approach in C
#include <stdio.h>

// Function to calculate the area of a rectangle
float calculateArea(float width, float height) {
return width * height;
}

int main() {
float width = 5;
float height = 10;
float area = calculateArea(width, height);

printf("Area of Rectangle: %.2f", area);
return 0;
}

In this procedural example, the function calculateArea() explicitly receives data (width, height) and returns a value without encapsulating the data and behavior into a unified entity.

Object-Oriented Programming (OOP)

OOP organizes programs into objects—units that encapsulate data (attributes) and behaviors (methods). This design mimics real-world entities, allowing developers to structure programs in a more natural, modular way. Initially, OOP was primarily employed in developing computer simulations (virtual models representing real-world systems) and Graphical User Interfaces (GUIs)—visual environments that allow user interaction via mouse clicks, keyboard inputs, or touch gestures. Today, its use has expanded dramatically, encompassing web applications, mobile development, game development, and more.

Characteristics of OOP:

  • Encapsulation: Data and methods bundled together in classes and objects.
  • Inheritance: Creating specialized subclasses from general parent classes.
  • Polymorphism: Methods behave differently based on the object calling them.
// Object-Oriented approach in C#
using System;

// Class representing a Rectangle object
class Rectangle
{
// Attributes (Properties)
public float Width { get; set; }
public float Height { get; set; }

// Method (Behavior)
public float CalculateArea()
{
return Width * Height;
}
}

class Program
{
static void Main()
{
// Create object instance
Rectangle rect = new Rectangle();
rect.Width = 5;
rect.Height = 10;

// Calculate and display area
Console.WriteLine($"Area of Rectangle: {rect.CalculateArea()}");
}
}

Here, the Rectangle class encapsulates data (Width, Height) and behavior (CalculateArea() method) together. This provides better organization, readability, and maintainability. Objects directly interact with their attributes through methods, reflecting real-world behaviors clearly and intuitively.

Key Differences at a Glance:

Procedural ProgrammingObject-Oriented Programming
Data separate from proceduresData and methods encapsulated together
Sequential flow of instructionsInteractive objects with defined behaviors
Emphasis on functionsEmphasis on classes, objects, and interactions
Less reusable, harder to scaleHighly reusable, modular, and scalable

OOP languages, including C#, are defined by several key principles:

  • Classes and Objects: A class defines the properties (attributes) and actions (methods) of potential objects. Objects are instances of these classes.
    • Example: A class Car might have attributes like color and speed, and methods such as Accelerate() and Brake().
  • Encapsulation: Bundling data (attributes) and methods into a single unit (class). Users interact with objects without needing to understand their inner workings, a concept often referred to as using a “black box.”
  • Inheritance: Creating specialized classes from general ones, inheriting attributes and methods.
    • Example: A general class Vehicle can be extended into a specific class like Car, adding unique properties like numDoors.
  • Polymorphism: Allowing methods to behave differently based on the object calling them.
    • Example: A method Draw() can produce different results when called by objects of classes like Circle or Square.

C#, developed by Microsoft, combines object-oriented programming with component-based architecture. It excels at creating modular and reusable components, crucial for modern application development. Unlike other languages like Java, every piece of data in C# is treated as an object, enhancing functionality and consistency.

Writing Your First C# Program

Here’s a simple C# program demonstrating basic output:

using System;

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

Explanation:

  • using System; lets you use built-in classes without fully qualifying their names each time.
  • Console.WriteLine() displays text and moves the cursor to the next line.
  • Main() method acts as the entry point for every executable C# application.

Creating and Naming Identifiers

Identifiers name classes, methods, and variables. Follow these rules when naming:

  • Begin with a letter, underscore (_), or @.
  • Can contain letters, numbers, underscores, and @.
  • Cannot use reserved keywords (like class, void) unless prefixed with @ (e.g., @class).

Comments in C#

Comments help document your code and explain logic without affecting execution. Types of comments include:

  • Single-line comment:
// This is a single-line comment
  • Multi-line comment:
/* This is a
   multi-line comment */
  • XML documentation comment:
/// <summary>
/// This method prints a greeting
/// </summary>

Efficient Namespace Usage

Namespaces organize related classes. Instead of repeatedly specifying a namespace, you can use a directive like:

using System;

// Now you can simply use:
Console.WriteLine("Hello!");

Using the Command Line

  1. Write and save your code in a text editor (e.g., Notepad).
  2. Open Developer Command Prompt for Visual Studio.
  3. Compile the program:
csc HelloWorld.cs
  1. Execute the compiled program:
HelloWorld.exe

Using Visual Studio IDE

Creating and running a C# console application in Visual Studio is straightforward. Here’s a step-by-step guide:

  1. Launch Visual Studio: Open Visual Studio and select Create a new project from the start screen.
  2. Select Project Type: In the project template dialog, search for and select Console App (.NET Framework) or Console App (.NET Core) depending on your preference. Click Next.
  3. Configure Project: Provide a project name, select a location to store your files, and choose the framework version. Click Create.
  4. Write Your Code: Visual Studio will open with a basic template already created.
  5. Build the Project: Compile your program by selecting Build → Build Solution from the top menu or pressing Ctrl + Shift + B. This will check your code for errors and compile it into an executable.
  6. Run the Application: Execute your compiled application by pressing F5 (Start Debugging) or by clicking the Start button (green play icon). You should see a console window displaying your message:
Hello, World!

Visual Studio’s IDE provides helpful features like syntax highlighting, auto-completion, error detection, and debugging, making your programming tasks easier and more efficient.

Conclusion

C# is a versatile and powerful programming language that streamlines the development of both simple and complex software. Understanding the fundamental principles and getting hands-on practice with writing and running code will set you on the path to becoming a proficient C# developer.

  • Microsoft. (2024). Introduction to C#. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/csharp/
  • Sharp, J. (2022). Microsoft Visual C# Step by Step (10th ed.). Microsoft Press.
  • Troelsen, A., & Japikse, P. (2021). Pro C# 9 with .NET 5: Foundational Principles and Practices in Programming (10th ed.). Apress.
  • Visual Studio. (2024). Getting started with Visual Studio IDE. Microsoft Visual Studio Documentation. https://visualstudio.microsoft.com/docs/

Leave a Reply

Your email address will not be published. Required fields are marked *