Multiple Classes in a Single Source File

This section provides a tutorial example on how to write multiple classes in a single C# source code file.

Unlike Java, C# allows you to write multiple classes in a single source file.

Here is a tutorial example C# source file that contains 2 classes, UtilTest.cs:

// UtilTest.cs
// Copyright (c) 2010 HerongYang.com. All Rights Reserved.

using System;
public class UtilTest {
   public static void Main() {
      string a = "blue";
      string b = "sky";
      Console.WriteLine("{0} {1}", a, b);
      Util.Swap(ref a, ref b);
      Console.WriteLine("{0} {1}", a, b);
   }
}
public class Util {
   public static void Swap(ref string x, ref string y) {
      string o = x;
      x = y;
      y = o;
   }
}

Note that:

If you compile and run this source file, you will get:

C:\herong>\Windows\Microsoft.NET\Framework\v4.0.30319\csc UtilTest.cs

C:\herong>UtilTest.exe
blue sky
sky blue

Table of Contents

 About This Book

 Introduction of C# (C Sharp)

 Data Type and Variables

 Logical Expressions and Conditional Statements

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

 Class Features

 C# Compiler and Intermediate Language

Compiling C# Source Code Files

 C# Compiler "csc" Options

Multiple Classes in a Single Source File

 Compiling Multiple Source Code Files Together

 Generating and Using .NET Library Files

 MSBuild - Microsoft Build Engine

 Memory Usages of Processes

 Multithreading in C#

 Async Feature from C# 5

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 WPF - Windows Presentation Foundation

 Partial Classes and Partial Methods

 Archived Tutorials

 References

 Full Version in PDF/ePUB