Ralvarez
Ralvarez

Reputation: 31

How to make a class partial class?

In these type of classes, can I make class ListBox a partial class? If yes, can someone show me some example. If no, can you briefly explain why?

namespace example 
{
    public class Control
    {
        private int top;
        private int left;
        public Control(int Top, int Left)
        {
            top = Top;
            left = Left;
        }
        public void DrawControl()
        {
            Console.WriteLine("Drawing Control at {0}, {1}", top, left);
        }
    }

    // how to make this class ListBox a partial class?
    public class ListBox: Control
    {
        private string mListBoxContents;
        public ListBox(int top, int left, string theContent): base(top,left)
        {
            mListBoxContents = theContent;
        }
        public new void DrawControl()
        {
            base.DrawControl();
            Console.WriteLine("Writing string to the ListBox: {0}", mListBoxContents);
        }
    }

    public class Tester
    {
        public static void Main()
        {
            Control myControl = new Control (5,10);
            myControl.DrawControl();
            ListBox lb = new ListBox (20, 30, "Hello World");
            lb.DrawControl();
        }
    }
}

Upvotes: 1

Views: 121

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156978

I am not sure what your intentions are but it as simple as this:

public partial class ListBox: Control
{ }

Partials classes are useful when using a designer that could mess up your code. This does not work across different assemblies. For some situations, abstract classes are more appropriate.

Upvotes: 0

Christos
Christos

Reputation: 53958

Of course you can. You can declare any class you want as partial. There isn't any case in which you can't. Just use the following declaration

public partial class ListBox: Control
{

}

However, I don't see the reason why you want to make this class partial. Usually, we use partial classes, when we want to split the definition of the class in two or more source files and make the code more readable and maintainable. For further documentation, please look here.

Upvotes: 2

Related Questions