Trouble with Using Namespace in C# and Unity!

Using an entire namespace doesn’t just cause issues in C++, it causes issues in other languages as well.

In fact, a common scenario is in Unity, which utilizes C# rather than C++.

For example, if you’re creating a random number, the code might be:

int randomNum = Random.Range(0,100);

This will assign a random number between 0 and 100, right? Wrong! It’ll print an error instead!

Why?

Because Unity automatically starts .cs script files with,

using UnityEngine;
using System.Collections;

The issue is that Random is part of both the UnityEngine namespace AND System.Collections!

I believe the reason is because either Unity or Collections uses entropy for its Random function, while the other is just a standard pseudorandom algorithm.

But the point is, if you just type “Random.Range( )”, you’ll get an error about "Random"s ambiguity. To fix this, you must write:

int randomNumer = UnityEngine.Random.Range(0,100);

Or the System Collections equivalent. This will tell the compiler which of the two identically named Random functions to use.

So in summary, “using namespace” isn’t just problematic in C++ and Unreal, but in a few languages! Even Python has this problem when including libraries with conflicting, ambiguous definitions, and Python has completely different syntax!

Overall, it’s just a limitation of computer programming in general. Or, rather, not a limitation, but an intentional warning to remind the programmer to be specific in their function calls.

Bonus:
However, this isn’t always the case! In many languages, you can “write a function twice”, called Overloading. What this means is that you can define a function with the same name, but with two different sets of arguments, so that the compiler “adapts” to the appropriate version.

For example, if you had a function that divided two numbers, but you wanted to handle it differently whether the user entered two integers or two floats, you could “overload” the function by defining it twice – once in a way that handles ints, another in a way that handles floats – and then when that function is later called, it can “adapt” (not really) based on what types of values the user or coder passes into it as arguments.

Furthermore, what is the difference between a parameter and an argument? Simply, a parameter is what you define in the function, an argument is what you pass to it.

Huh? They’re the same thing. It’s called a parameter when you’re writing and defining the function, but when you actually commit the act of passing a value into that parameter, the value you passed is an argument.

In any case, you can use both interchangeably and most programmers will understand what you mean.

Privacy & Terms