C#

Namespaces in C#

ยท 1 min read

Namespaces are like containers for classes, which can help us organize the code, we see the same concept in other programming languages such as Java, Python and other languages. The purpose of Namespace is to avoid variable or class conflicts and ambiguity. For example both of UnityEngine and System have the class name called Random. So we have to specify which namespace we are using.

create a namespace

Here is one example of creating namespace in csharp.

using UnityEngine;
using System.Collections;

namespace SampleNamespace {
  public class SomeClass: MonoBehaviour {
    void Start() {
      // some code here
    }
  }
}

Use a namespace

There are 3 ways of using a namespace:

// Method 1:
// import the namespace name on the top
using SampleNamespace;

// Method 2:
// use the dot to refer a class name from a namespace
SampleNamespace.SomeClass myClass = new SampleNamespace.SomeClass();

// Method 3:
// similar to create a class
namespace SampleNamespace {
  public class SomeClass2: MonoBehaviour {
    void Start() {
      SomeClass myClass = new SomeClass();
    }
  }

}