Overview of C# Programming Basics

Aug 29, 2024

C# Programming Basics

Introduction

  • C# is a flexible language for various applications: console apps, web services, games.
  • Average salary for C# developers: $63,000 per year.

Getting Started with C#

  • IDE Recommendation: Visual Studio Community
    • Download and install from the official website.
    • Check ".NET desktop development" for C# usage.

Creating a New Project

  • Open Visual Studio, create a new C# console application.
  • Adjust font size via Tools > Options > Environment > Fonts and Colors.

Basics of C# Programming

Hello World Example

  • Create a basic program to print "Hello World".
Console.WriteLine("Hello World");
  • Main Method:
    • Entry point of C# program.
    • Syntax: static void Main(string[] args) { }

Output Formatting

  • Output to console using Console.WriteLine().
  • Differentiate between Console.WriteLine() (new line) and Console.Write() (same line).

Variables in C#

  • Variables store data.
  • Declaration: int age;
  • Initialization: age = 21; or combined: int age = 21;
  • Use meaningful names for variables.

Constants

  • Constants are immutable values defined with const.
const double Pi = 3.14159;

Typecasting

  • Convert types explicitly.
int x = (int)3.14;  // x is 3

User Input

  • Accept input using Console.ReadLine() and convert it.
int age = Convert.ToInt32(Console.ReadLine());

Control Structures

If Statements

  • Basic syntax:
if (condition) { /* code */ } 
else { /* code */ }

Switch Statements

  • Efficient alternative to multiple if statements.
switch (variable) {
  case value:
    // code
    break;
}

Loops

While Loops

  • Executes while a condition is true.
while (condition) {
  // code
}

For Loops

  • Executes a specific number of times.
for (int i = 0; i < 10; i++) {
  // code
}

Classes and Objects

  • Class: Blueprint for objects.
  • Object: Instance of class.
  • Create properties and methods within classes.

Inheritance

  • Child classes inherit from parent classes.
  • Allows code reuse.

Polymorphism

  • Objects can be treated as instances of their parent class.
  • Enables dynamic method resolution.

Interfaces

  • Define contracts that implementing classes must follow.
  • Supports multiple inheritance.

Collections

  • Use collections (like lists) for dynamic data storage.
  • List Example:
List<string> names = new List<string>();
names.Add("Alice");

Exception Handling

  • Use try-catch blocks to handle potential errors in code execution.
try {
  // code
}
catch (Exception ex) {
  // handle exception
}

Conclusion

  • C# is a versatile language with a rich set of features for different programming tasks.