user6740100
user6740100

Reputation:

How to get value property from another class without inheritance in C#

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?

Upvotes: 0

Views: 1393

Answers (2)

Fabjan
Fabjan

Reputation: 13676

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);

Upvotes: 1

Mostafiz
Mostafiz

Reputation: 7352

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;
}

Upvotes: 0

Related Questions