0

I have classes:

public class Employee{

 public int Id {get;set;}
 public string Firstname {get;set;}

}

public class Person
{
   //get value Firstname property from Employee class
     Employee emp = new Employee();
     foreach(var s in emp)
     {
       Console.WriteLine(s.Firstname.ToList());
     }

}

So, I want to get value of property ex: Firstname from Person class.

(I'm newbie in C#)

How can I do that?

Fabjan
  • 13,506
  • 4
  • 25
  • 52
  • Have you any instance of `Employee` in `Person` class? If yes - then just access that instance `Firstname` property. – Andrey Korneyev Aug 22 '16 at 09:16
  • As your `Employee` isnt static, you need to create an instance out of it. – C4d Aug 22 '16 at 09:17
  • this isn't a teaching site and this is a very basic question. read up on C# and learn a little. By the power of google I summon thy teaching sites! https://www.google.co.il/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=learn%20c%23 – MichaelThePotato Aug 22 '16 at 09:17

2 Answers2

1

You can use aggregation (it's when Employee knows about Person and cannot operate without it). Example :

public class Employee
{    
   public int Id {get;set;}
   public string Firstname => Person.FirstName;
   public Person Person {get;private set;}

   // this ctor is set to private to prevent construction of object with default constructor
   private Employee() {}

   public Employee(Person person) 
   { 
       this.Person = person;
   }
}

public class Person
{
   // We add property to Person as it's more generic class than Employee
   public string Firstname {get;set;}
}

To create Employee you can use this code :

var jon = new Person { FirstName = "Jon" };
var employee = new Employee(jon);
Console.WriteLine(employee.FirstName); // OR
Console.WriteLine(employee.Person.FirstName);
Community
  • 1
  • 1
Fabjan
  • 13,506
  • 4
  • 25
  • 52
0

Your FirstName property is a string type so you can not interate over it by foreach loop you can only access it by this way

public class Employee{

 public int Id {get;set;}
 public string Firstname {get;set;}

 public Employee(string name)
 {
   this.Firstname = name;
 }

}

public class Person
{
   Employee emp = new Employee("Foo");
   string s = emp.Firstname;
}
Mostafiz
  • 7,243
  • 3
  • 28
  • 42