Adam Zacke Erlandsson
Adam Zacke Erlandsson

Reputation: 117

How to get value from another class (not Inheritance)

I'm trying to reach something from another class, but it won't work.

namespace grafiskdel_1_Adam_Erlandsson {
public partial class Form1 : Form
{
    public List<Arbetare> array;       

    public Form1()
    {
        InitializeComponent();
        this.array = new List<Arbetare>();
    }
}

Here is the code from my "Arbetare" class at the moment:

namespace grafiskdel_1_Adam_Erlandsson
{
   public class Arbetare : Person
    {

    }
}

This is a bit of code my Form1 class, and I'm trying to reach something from the class "Arbetare", but I can't reach it. My programmer teacher told me I can do this, or maybe I am doing something wrong?

I'm trying to reach a variable from the "Arbetare" class to put into my List<>. Just ask me if you got any questions :)

Upvotes: 0

Views: 172

Answers (2)

Goran
Goran

Reputation: 675

I think this is a problem of scoping, but I'm no C# guru.

Make sure you have the variable you want access to set as public.

Maybe this may help you?

http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.80).aspx

Upvotes: 0

dkackman
dkackman

Reputation: 15549

I think you are asking how to create a new instance of Arbetare and add it to the list.

public Form1()
{
    InitializeComponent();
    this.array = new List<Arbetare>();
    Arbetare v = new Arbetare();
    this.array.Add(v);

    Arbetrare v1 = this.array[0];

    // this will be true as v and v1 both point to the same instance
    System.Diagnostics.Debug.Assert(object.ReferenceEquals(v, v1));  
}

void SomeOtherMethod()
{
    // you can now access any of the items in your array and any of their properties
    // assuming of course some other code hasn't removed them 
    Arbetrare v1 = this.array[0];
}

Upvotes: 1

Related Questions