DEV Community

Cover image for Embark on the Code Crusade: A JavaScript Developer’s Venture into C#
Cindy Nguyen
Cindy Nguyen

Posted on

Embark on the Code Crusade: A JavaScript Developer’s Venture into C#

Do you want to sharpen your coding sword? Step into the dynamic world of C#. In this blog post, I’ll guide you through the transition from JavaScript to C#. As a JavaScript developer, you're about to embark on a thrilling journey through new syntax lands, past the towers of strict typing, and into the dungeons of object-oriented programming. We’ll explore why C# is worth learning, then compare it with JavaScript to highlight key similarities and differences. Along the way, I'll provide essential syntax examples to help you get started. Ready to conquer the challenges and emerge as a multi-language coding hero? Let the adventure begin!

Why C#?
C# is a versatile, high-level language developed by Microsoft. It is widely used in game development, enterprise software, and cross-platform applications.
Why is C# so popular?

  • Game Development: Its seamless integration with the Unity game engine has made it a favorite for game developers. Which is why I decided to learn it!
  • Enterprise Applications: It’s the go-to language for building desktop, web, and cloud-based applications due to the .NET framework
  • Cross-Platform Development: C# is used in frameworks that allow developers to create applications that work on Windows, macOS, Linux, iOS, and Android.

C# is the perfect balance between being easy to learn and packed with powerful features, making it the ultimate tool for leveling up your development skills and conquering new coding challenges!
Now that you know why C# is worth learning, let’s get into some basic syntax and compare it with JavaScript. This will give you a better understanding of how to translate your knowledge of JavaScript into your new C# development journey.

Tighten your grip on data types and variables
In C#, you'll find a much stricter approach to handling data types and variables compared to JavaScript. Here’s why:
C# is known as a statically-typed, strongly-typed language– meaning every variable must have a clear and specific data type (e.i string, int, bool, etc) that it sticks to throughout the code. This ensures you can’t perform operations that mix incompatible types—if you try, the program will throw an error before it even runs.

Whereas JavaScript allows variables to hold values of any type and even change their type later. JavaScript's implicit type coercion can sometimes lead to unexpected behavior, like adding a number-typed variable to a string without warning.

Syntaxally, in C# you would be replacing the keywords let or const with the appropriate data type. This change is something that still trips me up and sometimes frustrates me since I’m used to Javascript’s flexibility. But this rigorous system in C# serves a purpose: to catch type-related bugs earlier in development.

//Javascript example
let value = 42; //Value starts off as an integer
console.log(value + 10); // Output: 52
value = "Hello"; //Now value is declared as a string
console.log(value + 10); 
// Output: "Hello10" due to implicit coercion

//C# example
int value = 42; // Value is initialized as an integer
Console.WriteLine(value + 10); //Output: 52
value = value + "10";
//ERROR! Cannot add an int and string; mismatch data
value = "Hello";
//ERROR! value is defined as an int, no strings allowed
Enter fullscreen mode Exit fullscreen mode

Functions and Coding Blocks
Functions in both languages are used to encapsulate logic, but in C#, just like with variables, you need to state a function's return type explicitly. This contrasts with JavaScript, where functions don’t require a declared return type.

One of the biggest differences is that C# requires all code, including functions, to exist within a class. Even the simplest program must include a class and a "Main" method as the entry point. Unlike JavaScript, where you can write functions directly in the global scope, C# structures everything around classes. This design is due to the fact that C# is an object-orientated language, with classes every piece of code belongs to an object.

It’s safe to say, that if you want to get comfortable with C#, you’ll need to get comfortable with class structures and object-orientated programming.

//Javascript example
// A function without a declared return type
function addNumbers(a, b) {
    return a + b; // Automatically determines the return type
}

// Call the function directly in the global scope
const result = addNumbers(5, 3);
console.log("The result is: " + result);


//C# example
using System;

class Program // Class where our code exists
{
    // A function with an explicit return type
    static int AddNumbers(int a, int b)
    {
        return a + b; // Returns an integer
    }

    static void Main(string[] args) // Entry point
    {
        int result = AddNumbers(5, 3);
        Console.WriteLine("The result is: " + result);
    }
}


Enter fullscreen mode Exit fullscreen mode

Arrays, Lists, and Objects
When translating LeetCode solutions from JavaScript to C#, I quickly realized that just because two things share a name doesn’t mean they’re the same. For example, JavaScript arrays are more like C# Lists — flexible in size and typing, with built-in methods. C# arrays, on the other hand, are fixed-size and strictly typed, requiring LINQ for data manipulation. To handle key-value pairs in C#, you’d use a Dictionary, not an object. Unlike JavaScript, where objects are simply key-value pairs, C# objects are the base class for all data types.

//Javascript examples
// Arrays in JavaScript (flexible size and type)
let numbers = [1, 2, 3, "four"];
numbers.push(5); // Add an element
console.log(numbers); // [1, 2, 3, "four", 5]

// Key-value pairs with an object
let person = {
    name: "Alice",
    age: 30
};
console.log(person.name); // Access by key: "Alice"

// Add a new key-value pair
person.city = "New York";
console.log(person); // { name: "Alice", age: 30, city: "New York" }


//C# examples
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        // Arrays in C# (fixed size, strictly typed)
        int[] numbers = { 1, 2, 3 };
        // numbers[3] = 4; // Error: Out of bounds
        Console.WriteLine(string.Join(", ", numbers)); // 1, 2, 3

        // Lists in C# (flexible size and typed)
        List<object> mixedList = new List<object> { 1, 2, 3, "four" };
        mixedList.Add(5); // Add an element
        Console.WriteLine(string.Join(", ", mixedList)); // 1, 2, 3, four, 5

        // Dictionary for key-value pairs
        Dictionary<string, object> person = new Dictionary<string, object>
        {
            { "name", "Alice" },
            { "age", 30 }
        };
        person["city"] = "New York"; // Add a new key-value pair
        Console.WriteLine(person["name"]); // Access by key: Alice
    }
}

Enter fullscreen mode Exit fullscreen mode

Loops
From what I know, loops keep very similar syntax across both languages so… yay!
Initialize(remember to initialize with the data type in C#), Condition, increment!

//Javascript loop
for (let i = 0; i < 10; i++){
console.log(i);
}

//C# loop
for (int i = 0; i < 10; i++){
Console.WriteLine(i);
}
//remember, every time you initialize a variable 
//you must assign it a data type 
Enter fullscreen mode Exit fullscreen mode

The Key Differences Between C# and JavaScript
Typing: C# is static and strict Vs JavaScript is dynamic and flexible.
Model: C# is class-based OOP Vs JavaScript is prototype-based and multi-paradigm.
Compilation: C# is precompiled Vs JavaScript is executed line-by-line during runtime.
Syntax: C# enforces strict rules Vs JavaScript is more forgiving.

Tips for learning C# as a Javascript Developer
It’s dangerous to go alone! Take these strategies to make the learning process smoother:

  1. Leverage your Object-orientated programming knowledge
    C# is designed around classes and object-oriented principles. Since JavaScript also supports object-oriented programming with prototypes and ES6 classes, your existing understanding will make it easier to pick up C#, even though the two languages handle OOP differently.

  2. Start with the basics
    Familiarize yourself with the syntax differences, especially for variable declarations and functions. Unlike JavaScript, C# is a compiled language that enforces type safety, so you'll need to be more intentional with your code to avoid errors. Getting comfortable with these fundamentals early on will save you headaches down the road.

  3. Use comparisons to help bridge the gaps
    Creating a comparison chart between C# and JavaScript can help you clearly see their similarities and differences. It’s easier to understand new concepts when you have a familiar reference point. Plus, this approach highlights features unique to C#, like namespaces, access modifiers, and LINQ, which don’t have direct equivalents in JavaScript.

  4. Practice with simple, small projects
    If you want to get comfortable with C# quickly, building small console applications is the way to go. These projects let you practice using conditions, loops, arrays, and classes without feeling overwhelmed. I find the official documentation to be needlessly complicated and convoluted– making it easy to get discouraged when you’re trying to learn. Hands-on coding is the best way to build confidence and understanding!

Resources
Here are some FREE resources that might come in handy when trying to learn C#:
CodeCademy’s C# and .NET Course

Microsoft’s C# Fundamentals for Absolute Beginners

W3School’s C# Tutorial

Programiz’s C# Section

Conclusion
While the transition from JavaScript to C# may feel like arduously stepping into a much stricter realm in the programming world, the journey will be well worth it. By leveraging your JavaScript knowledge and embracing C#’s unique features, not only will you become a diverse developer but you will also gain skills that are highly valued in the industry. So go forth and conquer C#!

Top comments (0)