Public Group

# Pointers to Windows Forms C#

This topic is 3856 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm starting to work on pointers in C# and i understand how they work as far as normal variables go but i need to point to a windows form (or a least i think i do). Here's what i need to happen, maybe there is a better solution or maybe someone can help me with these pointers. I have two forms, i want one to change values of lets say a textbox or checkbox on the other. I know that the following code works but I'm trying to find a way of doing the same thing without creating 2 objects each of which equalling each other so that there is not double memory used.
[source lang=c#]
//what i'm trying to avoid
public partial class frmMain: Form
{
public frmMain()
{
...
InitializeFormObj(this);
}
}

public partial class ItemViewer : Form
{
private frmMain frm;

public InitializeFormObj(frmMain m_frm)
{
frm = m_frm;
}
}

[source lang=c#]
//what i was trying to do
public partial class ItemViewer : Form
{
unsafe frmMain* pFrm;

public void SendFormPointer(ref frmMain frm)
{
pFrm = &frm;
}
}

//SendFormPointer would be called from frmMain like this:
//SendFormPointer(this);

/*I realize the issue with my code is the fact that you can not declare a pointer
to a class like i have attempted. Any ideas how i can accomplish this task?*/



##### Share on other sites
Ok, after thinking over it for a while I realize that i could just make a Public function which can be sent data and then it alter the object values from within the frmMain class but is this the only way? My goal is knowledge not simply making this program work.

##### Share on other sites
Guess you didn't learn the difference in C# of by reference and by value, so I will try to explain it to you.

In C#, only structs and the internal base value types (int, short, byte, ect.) are treated by value. Everything else is treated by reference. A reference is kind of like a pointer to that object.

So in your case your two pieces of code are pretty much the same, except the top one is normal C# code.

Now with all of that said, you might want to switch over to observer type code to fix the problem you have there. What you can do is just have an event that the other for subscribes to, that will make the changes you want.

theTroll

##### Share on other sites
Thanks, i didn't realize that it automatically is sent byref with C# (still a noob)

##### Share on other sites
Since your goal is knowledge, then you really want to be doing this with events and delegates, not using direct access.

theTroll

1. 1
2. 2
3. 3
4. 4
Rutin
16
5. 5

• 12
• 9
• 12
• 37
• 12
• ### Forum Statistics

• Total Topics
631419
• Total Posts
2999976
×