using classes  
Author Message
Xelestial





PostPosted: Visual C# General, using classes Top

hi!

i don't know how to phrase my question but here it goes...

i have many functions in my program and they are all placed in the form1.cs what i want to do is separate it and place all of them in a class. how would i do this do i just copy it and now how can i call it in my program

thanks!



Visual C#9  
 
 
Paul Louth





PostPosted: Visual C# General, using classes Top

Firstly I'd suggest having a look through the book recommendations thread at the top of this forum.

You can extract pretty much any of the code in the form class and put it in your own, but you need to fix up any dependencies also.

Think about breaking items out by function and role. Group similar types of code. And don't group too much stuff together, try to keep your classes nice and manageable.

First create a class:

class MyClass

{
}

Then in your forms OnLoad just create an instance of it and save it in a private variable on the Form.

class Form

{

MyClass myClass;

protected override OnLoad(..)

{

// this instantiates your class

myClass = new MyClass();

}
}

You can then start adding methods to your class:

class MyClass

{

public void HelloWorld()

{

MessageBox.Show("Hello World");

}
}

You can then call that function from your form class:

class Form

{

MyClass myClass;

protected override OnLoad(..)

{

// this instantiates your class

myClass = new MyClass();

myClass.HelloWorld();

}
}

These are the real basics, and there's a whole load more stuff to learn, so I'd definitely recommend getting a decent book on C#, OO coding, and Windows Forms development.