Reputation: 1025
I have a class that contains some properties, and a class that inherits from that class that adds some additional properties. Unfortunately I can only get the inherited class from a data service. But I only need the properties on the superclass. How can this be accomplished?
I have the following classes:
namespace MA.ECCA.WebServices
{
public class Player
{
Public Player();
public string fname{get; set;}
public string lname{get; set;}
}
public class PlayerData : Player
{
public PlayerData();
public Stats stats {get; set;}
}
}
Given an object of type PlayerData how could I get an object with only the Player properties?
I have tried the following:
Player player = GetPlayerStats();//returns object of type PlayerStats populated with data
and...
Player player = (Player)GetPlayerStats();
In both cases I end up with all the data, I only want an object that contains the fname and lname...
Upvotes: 0
Views: 512
Reputation: 12954
As I understand correctly, the method GetPlayerStats
always returns an object of type PlayerData
. And I understand this cannot be changed and you want to receive less data (no statistics, only the first and last name).
The object of a certain type always stay the same; it will always maintain the same members. It will not suddenly get smaller. Casting it up to a Player
or even an object
will make some/all properties less visibility, but they are still inside that object.
In your case you should create a totally new instance of type Player
and copy the data from the first object to the new one. For example:
public class Player
{
public Player();
public Player(Player original)
{
fname = original.fname;
lname = original.lname;
}
public string fname{get; set;}
public string lname{get; set;}
}
...
PlayerData playerData = GetPlayerStats();
Player player = new Player(playerData);
If you do this often, you might consider creating a generic method and use reflection to copy properties from the first object to the next.
Upvotes: 2