Menu
Coddy logo textTech

External Files

Part of the Object Oriented Programming section of Coddy's C# journey — lesson 1 of 70.

External files let you organize your classes in separate C# files and reference them in your main program using namespaces.

Create a separate C# file called MyClass.cs

namespace MyApp
{
    public class MyClass
    {
        public string Name { get; set; }
        
        public MyClass(string name)
        {
            Name = name;
        }
        
        public string Greet()
        {
            return $"Hello, I'm {Name}";
        }
    }
}

Reference the namespace in your main file

using MyApp;

Create an instance and use it

MyClass obj = new MyClass("Alice");
Console.WriteLine(obj.Greet());

Output:

Hello, I'm Alice

The using MyApp; statement allows you to use classes from the MyApp namespace without fully qualifying them. The namespace groups related classes together, and classes must be public to be accessible from other files.

challenge icon

Challenge

Medium

You are given C# files (MyClass.cs and Program.cs), add a using statement in the Program.cs file to connect the files and use the class from the external file!

Cheat sheet

External files let you organize classes in separate C# files and reference them using namespaces.

Create a separate C# file with a namespace:

namespace MyApp
{
    public class MyClass
    {
        public string Name { get; set; }
        
        public MyClass(string name)
        {
            Name = name;
        }
        
        public string Greet()
        {
            return $"Hello, I'm {Name}";
        }
    }
}

Reference the namespace in your main file using the using statement:

using MyApp;

Create an instance and use it:

MyClass obj = new MyClass("Alice");
Console.WriteLine(obj.Greet());
// Output: Hello, I'm Alice

Classes must be public to be accessible from other files. The using statement allows you to use classes from a namespace without fully qualifying them.

Try it yourself

// TODO: Replace the ? with the correct namespace to use MyClass
using ?;
using System;

class Program
{
    static void Main()
    {
        string testCase = Console.ReadLine();
        // Create an instance of MyClass and call GetMessage()
        MyClass obj = new MyClass();
        Console.WriteLine(obj.GetMessage());
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming