2- Getting Started with C# for Java Developers

image 2

Play Store Application link – Java to .NET in 9 Steps – App on Google Play

Welcome back! In this post, we’ll dive into the basics of C# for developers who are already familiar with Java. We’ll cover the fundamental syntax, object-oriented programming concepts, and exception handling. I’ll provide real-world examples and draw comparisons with Java to make the transition smoother.


1. C# Basics

Data Types and Variables

In C#, just like in Java, you define variables to store data. Here’s a quick look at some common data types:

  • Integer: int (e.g., int age = 30;)
  • Floating-point: double (e.g., double price = 19.99;)
  • Boolean: bool (e.g., bool isActive = true;)
  • Character: char (e.g., char grade = 'A';)
  • String: string (e.g., string name = "John";)

Example Code:

int age = 30;
double price = 19.99;
bool isActive = true;
char grade = 'A';
string name = "John";

Operators and Expressions

Operators in C# are quite similar to Java’s. Here are a few examples:

  • Arithmetic Operators: +, -, *, /
  • Comparison Operators: ==, !=, >, <
  • Logical Operators: &&, ||, !

Example Code:

int a = 10;
int b = 5;
int sum = a + b; // sum is 15
bool isEqual = (a == b); // false
bool isNotEqual = (a != b); // true

Control Structures

C# uses similar control structures to Java:

  • If Statements: Conditional execution.
  • Switch Statements: Multiple branching based on values.
  • Loops: for, while, do-while.

Example Code:

// If statement
if (age > 18)
{
    Console.WriteLine("Adult");
}
else
{
    Console.WriteLine("Not an adult");
}

// Switch statement
switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent");
        break;
    case 'B':
        Console.WriteLine("Good");
        break;
    default:
        Console.WriteLine("Needs Improvement");
        break;
}

// For loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

// While loop
int count = 0;
while (count < 5)
{
    Console.WriteLine(count);
    count++;
}

2. Object-Oriented Programming

Classes and Objects

In C#, classes and objects are similar to Java. A class defines the blueprint, while objects are instances of that class.

Example Code:

class Person
{
public string Name { get; set; }
public int Age { get; set; }

public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}

Person person = new Person();
person.Name = "Alice";
person.Age = 25;
person.Introduce();



Inheritance

Inheritance allows a class to inherit properties and methods from another class. In C#, it’s similar to Java’s extends.

Example Code:

class Employee : Person
{
    public string JobTitle { get; set; }

    public void DisplayJob()
    {
        Console.WriteLine($"Job Title: {JobTitle}");
    }
}

Employee employee = new Employee();
employee.Name = "Bob";
employee.Age = 30;
employee.JobTitle = "Software Developer";
employee.Introduce();
employee.DisplayJob();

Polymorphism

Polymorphism allows methods to be overridden in derived classes. It’s similar to Java’s method overriding.

Example Code:

class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

Animal myDog = new Dog();
myDog.MakeSound(); // Outputs: Bark

Encapsulation

Encapsulation means restricting access to certain details of an object. In C#, we use access modifiers like public, private, and protected.

Example Code:

class BankAccount
{
    private double balance;

    public void Deposit(double amount)
    {
        if (amount > 0)
        {
            balance += amount;
        }
    }

    public double GetBalance()
    {
        return balance;
    }
}

BankAccount account = new BankAccount();
account.Deposit(100);
Console.WriteLine(account.GetBalance()); // Outputs: 100

3. Exception Handling

Try-Catch Blocks

C# handles exceptions similarly to Java with try, catch, and finally.

Example Code:

try
{
    int result = 10 / 0; // This will cause a divide-by-zero exception
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
}
finally
{
    Console.WriteLine("This will always execute.");
}

Custom Exceptions

You can create custom exceptions by extending the Exception class.

Example Code:

class CustomException : Exception
{
    public CustomException(string message) : base(message)
    {
    }
}

try
{
    throw new CustomException("This is a custom exception");
}
catch (CustomException ex)
{
    Console.WriteLine(ex.Message);
}

This overview should give you a good starting point in C# while leveraging your Java knowledge. As you get more comfortable with the language, you’ll find many similarities and some differences that make C# unique. Happy coding!

Leave a Reply

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