3- Advanced C# Features for Java Developers

image 2

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

Welcome back! If you’re a Java developer stepping into the world of C#, you’ll find many advanced features that can enhance your coding experience. In this post, we’ll dive into some of the more advanced C# concepts, including generics, collections, LINQ, and delegates. We’ll use real-world examples and draw comparisons to Java where applicable to make the transition easier.


1. Generics

Generics in C# allow you to define classes, methods, and data structures with a placeholder for the data type. This is similar to Java’s generics.

Generic Classes and Methods

In Java, you might define a generic class like this:

public class Box<T> {
private T content;

public void setContent(T content) {
this.content = content;
}

public T getContent() {
return content;
}
}

In C#, the syntax is almost identical:

Example Code:

public class Box<T>
{
private T content;

public void SetContent(T content)
{
this.content = content;
}

public T GetContent()
{
return content;
}
}

Using Generics:

Box<int> intBox = new Box<int>();
intBox.SetContent(123);
Console.WriteLine(intBox.GetContent()); // Outputs: 123

Box<string> stringBox = new Box<string>();
stringBox.SetContent("Hello, C#");
Console.WriteLine(stringBox.GetContent()); // Outputs: Hello, C#

Constraints

Constraints in C# allow you to restrict the types that can be used with generics. This is similar to Java’s bounded type parameters.

Example Code:

public class Repository<T> where T : class
{
public void Add(T item)
{
// Add item to the repository
}
}

2. Collections

Collections in C# are a set of classes that hold groups of related objects, similar to Java’s collections framework.

Lists, Dictionaries, Queues

Lists in C# are akin to Java’s ArrayList:

Example Code:

List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
Console.WriteLine(fruits[1]); // Outputs: Banana

Dictionaries are similar to Java’s HashMap:

Example Code:

Dictionary<string, int> ageDict = new Dictionary<string, int>();
ageDict["Alice"] = 30;
ageDict["Bob"] = 25;
Console.WriteLine(ageDict["Alice"]); // Outputs: 30

Queues work like Java’s Queue interface:

Example Code:

Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
Console.WriteLine(queue.Dequeue()); // Outputs: First

3. LINQ (Language Integrated Query)

LINQ allows you to query collections in a more readable and declarative way. It’s similar to Java Streams.

Example Code:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = from n in numbers
where n % 2 == 0
select n;

foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Outputs: 2, 4
}

4. Delegates and Events

Delegates are like Java’s interfaces used for callbacks. They allow methods to be passed as parameters.

Delegates Basics

Example Code:

public delegate void Notify(string message);

public class Process
{
public event Notify OnProcessCompleted;

public void StartProcess()
{
// Process logic here
OnProcessCompleted?.Invoke("Process completed!");
}
}

Using Delegates:

Process process = new Process();
process.OnProcessCompleted += message => Console.WriteLine(message);
process.StartProcess(); // Outputs: Process completed!

Lambda Expressions

Lambda expressions are a concise way to write anonymous methods, similar to Java’s lambda expressions.

Example Code:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var squares = numbers.Select(x => x * x);

foreach (var square in squares)
{
Console.WriteLine(square); // Outputs: 1, 4, 9, 16, 25
}

Event Handling

Events are used to provide notifications to other parts of the program, similar to Java’s event listeners.

Example Code:

public class Alarm
{
public event Action<string> AlarmRang;

public void Ring(string message)
{
AlarmRang?.Invoke(message);
}
}

Alarm alarm = new Alarm();
alarm.AlarmRang += message => Console.WriteLine(message);
alarm.Ring("Alarm is ringing!"); // Outputs: Alarm is ringing!

This guide should help you grasp some of the advanced features in C# with ease, leveraging your Java experience. By exploring these concepts, you’ll find that many of them closely align with Java features, while also discovering unique aspects of C# that can enhance your development skills. Happy coding!

Leave a Reply

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