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. Within a single project, classes are accessible across files by default; marking a class public is what makes it accessible from other projects (assemblies) as well.

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!

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