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 AliceThe 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
MediumYou 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());
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator