Can I split my C# class across multiple files?

Yes, you can use partial classes. This allows you to split your class over multiple files.

File 1:

public static partial class ReferenceData
{
    /* some methods */
}

File 2:

public static partial class ReferenceData
{
    /* some more methods */
}

Use this feature carefully. Overuse can make it hard to read the code.


Yes, include the keyword partial in the class declaration in every file where you do so.

http://msdn.microsoft.com/en-us/library/wa80x488.aspx


Yes you can of course, just use the partial keyword before the class keyword at all declarations. For example, make 4 different files (but in the same namespace) containing methods and members for the ReferenceData class like this:

File1.css

public static partial class ReferenceData
{

    public static IEnumerable<SelectListItem> GetAnswerType()
    {
        return new[]
            {
                new SelectListItem { Value = "1", Text = "1 answer"  },
                new SelectListItem { Value = "2", Text = "2 answers" },
                new SelectListItem { Value = "3", Text = "3 answers" }
            };
    }
}

File2.cs

public static partial class ReferenceData
{

    public static IEnumerable<SelectListItem> GetDatastore()
    {
        return new[]
            {
                new SelectListItem { Value = "DEV", Text = "Development"  },
                new SelectListItem { Value = "DC1", Text = "Production" }
            };
    }
}

File3.cs

public static partial class ReferenceData
{

    public static string GetDatastoreText(string datastoreValue)
    {
        return GetDatastore().Single(s => s.Value == datastoreValue).Text;
    }
    public static string GetDatastoreValue(string datastoreText)
    {
        return GetDatastore().Single(s => s.Text == datastoreText).Value;
    }
}

File4.cs

public static partial class ReferenceData
{

    // Lots more here
    // Lots more here
}

Tags:

C#