James
James

Reputation: 51

Creating a class object in C#

I am trying to create an object of a class, but it doesn't seem to work, I can't help but think I am looking at this from a JAVA perspective:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            PortChecks PortCheckObject = new PortChecks();

        }

private void testCheck_Click(object sender, EventArgs e)
        {
            PortCheckObject.MyMethod();
        }

I can error when using the PortCheckObject to call my method MyMethod

(PortChecks is the class name)

Upvotes: 2

Views: 170

Answers (5)

Max
Max

Reputation: 96

This is a general scope issue, not a Java v.s. C# issue (as your code wouldn't work in Java either). PortCheckObject is in Form1()'s scope, not testCheck_Click's scope. Try the following:

public partial class Form1 : Form
{
    private PortChecks PortCheckObject;

    public Form1()
    {
        InitializeComponent();

        PortCheckObject = new PortChecks();

    }

private void testCheck_Click(object sender, EventArgs e)
    {
        PortCheckObject.MyMethod();
    }

Upvotes: 1

Bruno Arueira
Bruno Arueira

Reputation: 314

@James,

You need a class property with the name 'PortCheckObject' and can be possible to access in other parts of the class.

public partial class Form1 : Form
{
    private PortChecks PortCheckObject;

    public Form1()
    {
        InitializeComponent();

        PortCheckObject = new PortChecks();
    }

    private void testCheck_Click(object sender, EventArgs e)
    {
        PortCheckObject.MyMethod();
    }
}

Upvotes: 2

Kevek
Kevek

Reputation: 2554

This is an instance of a scope problem. You do not have scope in your testCheck_Click method. Make the following change and it should work:

public partial class Form1 : Form
{
    private PortChecks MyPortCheck {get; set;}

    public Form1()
    {
        InitializeComponent();
        MyPortCheck = new PortChecks();
    }

    private void testCheck_Click(object sender, EventArgs e)
    {
        MyPortCheck .MyMethod();
    }

...
}

Upvotes: 0

Sergey Metlov
Sergey Metlov

Reputation: 26291

PortChecks PortCheckObject in Form1 constructor is a local variable.
Put its declaration as a private field in Form1 class.

public partial class Form1 : Form
{
    private PortChecks PortCheckObject = new PortChecks();

    public Form1()
    {
        InitializeComponent();
    }

    private void testCheck_Click(object sender, EventArgs e)
    {
        PortCheckObject.MyMethod();
    }
}

Upvotes: 3

msarchet
msarchet

Reputation: 15232

It's because it's outside of the scope of testCheck_Click

public partial class Form1 : Form
{
    PortChecks PortCheckObject = new PortChecks();

    public Form1()
    {
        InitializeComponent();
    }

    private void testCheck_Click(object sender, EventArgs e)
    {
        PortCheckObject.MyMethod();
    }
}

Upvotes: 9

Related Questions