You'd simply define a base class (you could make it abstract):
public abstract class Named
{
public string Name { get; set; }
}
and inherit from it:
public class Person : Named
{
}
You don't really need isNamed
as in C#, it is perfectly safe to compare strings with ==
.
If your class already inherits from another class which is not Named
, you'll have to manually add the Name
auto property or resort to simulated multiple inheritance.
Alternatively, you could create a specific modification of Named
for every base class:
public abstract class NamedLifeForm : LifeForm
{
public string Name { get; set; }
}
public class Person : NamedLifeForm
{
// Person inherits both a Name and all relevant members of LifeForm
}
Another alternative would be to create a generic wrapper, Named<T>
, that would have two properties: the Name
and an instance of T
. But that would make construction and access cumbersome, so I don't recommend it.