C# vs Javascript 

My more or less serious way in programming started with writing programs in C#, sometimes I tried to write in JavaScript, and now and then I got stumped in such situations, when I had incorrectly specified variable name and found out about it many years later after many hours of debugging, because I did not…

My more or less serious way in programming started with writing programs in C#, sometimes I tried to write in JavaScript, and now and then I got stumped in such situations, when I had incorrectly specified variable name and found out about it many years later after many hours of debugging, because I did not have my compiler, which would help me in a difficult moment. After a while, in addition to C# I started writing a lot of code in JavaScript and now I can do it without much difficulty, I am no longer confused by implicit type conversions and dynamic typing.

In this article I would like to systematize my basic knowledge of these languages and review their similarities and differences. This article can serve as a guide for C# developers who want to learn JavaScript and vice versa. I also want to note that this article describes the features of client-side JS since I have no experience with Node.js. So, if you are still interested, let’s get started.

Namespace and js-modules

In every program, in order to avoid conflicts in the names of variables, functions, classes or other objects, we combine them into some spaces. That way, if two different spaces contain elements with the same names, there will be no conflict.

In C#, namespaces are used to divide a program into parts. The keyword namespace is used to declare them. For example, if we want to create a set of user interface components, it is logical to put them all into one namespace, for example Components. In this case it is accepted that the namespace has the following namespace name [AssemblyName].[DirectoryName].[…]. In each file you need to put the component class of the user interface inside of the namespace:

The contents of the file ComboBox.cs:

namespace AssemblyName.Components
    public class ComboBox 
        // ...

Для того, чтобы начать использовать компоненты необходимо импортировать их из пространства имён следующим образом using AssemblyName.Components. При данном способе подключения одной строкой мы импортируем все объекты в текущий файл.

В JS для этих же целей применяются ES-модули. При их использовании мы в какой-то степени эмулируем поведение пространств имен написанием дополнительного кода. Рассмотрим тот же пример с библиотекой компонентов. Допустим у нас есть папка Components, которая содержит компоненты пользовательского интерфейса ComboBox.jsCheckbox.jsButton.js и тд. Для того чтобы получить схожее поведение по сравнению с пространством имен в папке Components необходимо создать файл index.js, который будет содержать следующий код:

export { default as Dialog } from './ComboBox';
export { default as Button } from './Button';
export { default as Checkbox } from './Checkbox';
// ...

In order to use these components it is necessary to import them into the current file. It can be done as follows: import * as Components from ‘./../Components’, after the keyword from we need to specify the path to the folder where all the described components are located.

Variable declaration methods

Keyword var

C# is known to be a strictly typed programming language, so the compiler needs to know the type of the variable.

double pi = 3.14;
User user = new User();
int[] a = new[] { 0, 1, 2 };

But we can also tell the compiler that it should derive the type itself from the expression after the assignment sign. This was made possible by the introduction of the var keyword in C# 3.0.

// i - int
var i = 5;

// a - int[]
var a = new[] { 0, 1, 2 };

With var we can create objects of anonymous type:

// anon - Anonymous read-only type
var anon = new { Name = "Terry", Age = 34 };
var type = anon.GetType();//"<>f__AnonymousType0`2"

In JavaScript you can also use the var keyword to declare variables, but unlike C# the scope of these variables will be the entire function or window object if the variable was declared outside the function.

var a = 5 // visibility area - window

function go() {
  var a = 6 // scope - go function

  // ...

Although you have the option of declaring variables with var in JavaScript, it is not recommended to do so now, since the ES6 standard was released the let keyword was added, which also allows you to declare variables, but its advantage is that their scope will be the block in which they are declared, not the entire function.


Both C# and JavaScript use the keyword const to declare a constant field. However, it should be noted that the concept of a constant in this case is different for these languages.

In C# constant is an expression that can be evaluated at compile time, i.e. it can be a number, a logical value, a string or a null reference.

const int c1 = 5;
const int c2 = c1 + 100;
const string c3 = "Константа";
const bool c4 = true;

const User human = null;
const User human = new User(firstName); //Invalid, compilation error

In JavaScript, the value of a constant also cannot be changed, but there are no restrictions placed on the value as in C#, any values/objects/arrays can be assigned to it. However, if an object is assigned to a constant, then the constant itself is protected from modification, but not the properties within it:

const c1 = 5;
const c2 = c1 + 100;
const c3 = "Constant";
const c4 = true;

const user = {
  name: "Petya"

user.name = "Petya"; // allowed
user = 5; // impossible, there will be an error

The void keyword

While writing this article I was experimenting with functions in the console and out of habit started describing a function as in C# void SomeFunction…, and it came as a big surprise to me when I found out that JavaScript has void keyword. As it turns out, void in JavaScript is a unary operator that calculates the value of an operand, then discards it and returns undefined.

alert("Hello!"); // "Hello!"
alert(void "Hello!"); // undefined

So, we can say that using void explicitly indicates that there is no return value, you can read more examples of its use in the next article.

In C# void is not an operator, but in essence it has a similar meaning. Here it indicates that there is no return value for the function:

public void SampleMethod()
// …

However, as you can see in the example above, void stands in the place where the type of the return value is usually specified, and this is no accident, because void is also a type in C#.

var t = typeof(void);
t.Name // System.Void

Void as a type can only be used in an unsafe context when working with pointers.

void* identifier; // allowed, but not recommended

The new keyword

In JavaScript, the keyword new is an operator, and is used in the usual way for many C-like languages – to create an object.

function Animal() {
const animal = new Animal();

In C# new can be used for the following purposes:

  • to create objects;
  • to hide an inherited member of a base class;
  • to restrict the types that can be used as arguments to a type parameter in a generic class.

The first case is similar to using new in JavaScript.

class Animal
var animal = new Animal();

Basic data types

Every language has data types, primitives, on the basis of which other data types are built. Let’s see the data types provided to us in C# and JavaScript.

C# primitive types:

  • Integer with sign: sbyte, short, int, long
  • Unsigned integer: byte, ushort, uint,ulong
  • Unicode Characters: char
  • Unicode character set: char
  • Floating point numbers: float, double
  • Incremental decimal: decimal
  • Logical value: bool

The base class is Object.

For JS:

Primitive data types:

  • number number
  • string
  • Logic type boolean
  • Special value null
  • Special value undefined
  • symbol

The base type is Object.

After studying the primitives of both languages, we can come to the following conclusions:

  • Instead of a fairly large number of numeric types, JavaScript has a single type, number;
  • JavaScript doesn’t have a char type and should use the string type instead;
  • In both languages, the base type is Object;
  • A distinctive feature of JS is that null and undefined are separate types, whereas in C# null is a keyword denoting no value.
  • The symbol type is present in JS, which is mainly used within the JavaScript standard itself, in order to be able to add new functionality without conflicting with the existing code base.

Typically, there are now more and more applications where you need to do data processing on the client, which requires more precision in calculations. Currently JavaScript does not have a built-in capability to handle large numbers, but a new BigInt type is planned to be added in the near future. There is a class System.Numerics.BigInteger.

In this article we have discussed only the most basic concepts of C# and JavaScript. But there are still many aspects we haven’t touched on:

  • collections
  • functions
  • classes
  • multithreading .

Each of these topics is quite extensive and will be covered in a later article.

Similar Posts

Leave a Reply

Your email address will not be published.