Reputation: 307
There was a question asked by interviewer for C#:
One public class having 5 public members. A person wants an object which consumes 2 members and another to consume all 5 members. How to achieve this ?
I could not understand this. Can anyone please help what did it meant ? What would be a situation where something as above would be required ?
Upvotes: 2
Views: 77
Reputation: 460340
Well, it's hard to tell if this is what the interviewer wanted to hear. You should have asked what exactly he means with Person and consume.
I guess he wanted to hear that you understand for what interfaces are:
public interface IPerson: IHaveName
{
DateTime DateOfBirth {get;set;}
string MainAddress {get;set;}
string MainPhoneNumber {get;set;}
}
public interface IHaveName
{
string FirstName {get;set;}
string LastName {get;set;}
}
public class Person: IPerson
{
public string FirstName {get;set;}
public string LastName {get;set;}
public DateTime DateOfBirth {get;set;}
public string MainAddress {get;set;}
public string MainPhoneNumber {get;set;}
}
Now you can pass the Person
to a method that needs to consume the whole Person
or a method that just needs to consume the Name:
public static void Main()
{
Person p = new Person(); // skip initialization
ConsumePerson(p);
ConsumeNames(p);
}
public static void ConsumePerson(IPerson person)
{
// do something with the whole Person object
}
public static void ConsumeNames(IHaveName name)
{
// do something with just the FirstName/LastName
}
Upvotes: 2