Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Passing struct from one object to another

Tags:

c#

struct

I'm trying to pass a struct from one object to another. I have the following code:

    private void mainMenuStripNewProject_Click(object sender, EventArgs e)
    {
        frmNewProject frmNewProject = new frmNewProject(this);
        if (frmNewProject.ShowDialog() == DialogResult.OK)
        {
            StructProjectSettings tempProjectSettings = frmNewProject.getSettings();
            newProjectEvent(tempProjectSettings);                   //Fetchs settings from the new project form
        }
    }

However, I get the following error:

Error 14 Cannot implicitly convert type 'NathanUpload.frmNewProject.StructProjectSettings' to 'NathanUpload.Main.StructProjectSettings' o:\daten\visual studio 2010\Projects\NathanUpload\NathanUpload\Main.cs 43

The structs in each class are declared public class variables and are identical.

Thanks for the help in advance!

like image 763
nf313743 Avatar asked Dec 07 '22 01:12

nf313743


1 Answers

Have you defined the actual struct inside each of the classes?

Even if you use the same name on them, the compiler won't treat them as the same type.

You have to define the struct in one place, and make object of it from both classes that needs to use it.

An example

public class A{
  public struct MyStruct{
    ...
  }
}

public class B{
  public struct MyStruct{
    ...
  }
}

A.MyStruct struct1 = new B.MyStruct();

This is not allowed, and this is actually what you are trying to do. I suggest moving the struct out of the class and put it somewhere both classes can access it.

Define it like this instead

public struct MyStruct{
  ...
}

public class A{
  ...
}

public class B{
  ...
}

MyStruct struct1 = new MyStruct();
like image 52
Øyvind Bråthen Avatar answered Dec 09 '22 13:12

Øyvind Bråthen