this is strange but I really need it. I need to inherit a class without inherit their base class but I don't know how.
I have a base abstract entity class from a framework like this:
public abstract class AbstractEntity
{
public bool Validate(){};
public List<ValidationErrors> erros;
// and so many more properties and methods
}
My custom class inherit this abstract base class:
public class Contact : AbstractEntity
{
public int id
public string name;
public string phone;
}
I'm using this class Contact on a webservice and I need only the custom properties, how can I re-use the class Contact without the inheritance AbstractEntity?
I don't want to duplicate this class. Sorry if this sounds stupid.
EDIT
This is a project already created with a code generator, I can't change the classes structures. For this reason I wanted to instantiate that class without the abstract class.
As I can not change it now and need it urgently, I will duplicate this class without the abstraction and use it.
Sounds like you need an interface.
Extract an interface (IAbstractEntity) from AbstractEntity. Or maybe IContact from Contact- the question isn't very clear about which class has the methods and properties that you want to share. It would looks something like this:
public interface IContact
{
int Id { get; }
string Name { get; }
string Phone { get; }
}
Implement IContact on Contact. Then modify any methods that only use the particular methods/properties in IContact to use an IContact instead of Contact.
And I agree with #Jamie-Penney, it sounds like you should read http://en.wikipedia.org/wiki/Data_transfer_object
Finally, if this is a DTO, you are probably going to find yourself in need of something like AutoMapper
As far as I know you cannot break the inheritance chain. If you want a Contact that doesn't inherit AbstractEntity, you must create a new Contact class that doesn't list AbstractEntity as a parent.
Sorry, that's just how C# is designed.
Try containment.
public class NotAnEntity
{
public Contact { get; set; }
public static implicit operator Contact(NotAnEntity other)
{
return other.Contact;
}
}
While I think that using a simple DTO would probably be the easiest solution, another option would be to implement the IXMLSerializable interface on your Contact class and have it only serialize the properties you care about. Of course, this would affect the XML serialization of the object in other situations as well, not just with the web services.
Related
I'm not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I'll try to make a simple example. Let's say I have this:
abstract class Human
{
public GenderType Gender { get; set; }
public string Name { get; set; }
public Date Born { get; set; }
public bool IsNerd { get; set; }
abstract public void Speak();
abstract public void Sleep();
abstract public void AnoyingPeopleOnStackOverflow();
//... so on
}
class Peter : Human
{
//Peter is special, he got a second name
//But thats all, everything else is the same as like on other humans
public string SecondName { get; set; }
//...override abstract stuff
}
Is this alright? As I understood, I don't have to use an abstract property if I dont want to override it. And in this situation it would be ok, just the methods like Speak, Sleep and so on should be abstract.
Now, if this is ok, when would or should I use an abstract property?
Use an abstract property when you have no default implementation and when derived classes must implement it.
Use a virtual property when you have an implementation in the base class but want to allow overriding.
Use the override keyword to override a member. Mark the member as sealed override if it should not be overridden again.
Don't mark the property as abstract or virtual if you don't want it to be overridden.
Use the new keyword to hide a non-abstract, non-virtual member (this is rarely a good idea).
How to: Define Abstract Properties
I find that abstract properties often occur in a design which implies that they will have type-specific logic and/or side effects. You are basically saying, "here is a data point that all subclasses must have, but I don't know how to implement it". However, properties which contain a large amount of logic and/or cause side effects may not be desirable. This is an important consideration, though there is no fixed right/wrong way to do it.
See:
Should Properties have Side Effects
CA1024: Use properties where appropriate
Personally, I find that I use abstract methods frequently but abstract properties rarely.
I know what I want them to do, I don't care how they do it: Interface.
I know what I want them to do, I don't care how they do some of it, but I've firm ideas on how they'll (or at least most of them) do other bits: Abstract class.
I know what I want them to do, and how most of them will do it: Concrete class with virtual members.
You can have other cases such as e.g. an abstract class with no abstract members (you can't have an instance of one, but what functionality it offers, it offers completely), but they're rarer and normally come about because a particular hierarchy offers itself cleanly and blatantly to a given problem.
(Incidentally, I wouldn't think of a Peter as a type of Human, but of each peter as an instance of human who happens to be called Peter. It's not really fair to pick on example code in this way, but when you're thinking about this sort of issue it's more pertinent than usual).
Abstract members are simply virtual members that you have to override. You use this for something that has to be implemented, but can't be implemented in the base class.
If you want to make a virtual property, and want that it has to be overridden in the class that inherits your class, then you would make it an abstract property.
If you for example have an animal class, its ability to breathe would not be possible to detemine just from the information that it's an animal, but it's something that is pretty crucial:
public abstract class Animal {
public abstract bool CanBreathe { get; }
}
For a fish and a dog the implementation would be different:
public class Dog : Animal {
public override bool CanBreathe { get { return !IsUnderWater; } }
}
public class Fish : Animal {
public override bool CanBreathe { get { return IsUnderWater; } }
}
Use abstract when all sub-classes have to implement the method/property. If there's no need for each and every sub-class to implement it, then don't use it.
As for your example, if SecondName is not required for each person, then there's no need to make an abstract property in the base class. If on the other hand, every person does need a second name, then make it an abstract property.
Example of correct usage of an abstract property:
public class Car
{
public abstract string Manufacturer { get; }
}
public class Odyssey : Car
{
public override string Manufacturer
{
get
{
return "Honda";
}
}
}
public class Camry : Car
{
public override string Manufacturer
{
get
{
return "Toyota";
}
}
}
Making Maker abstract is correct because every car has a manufacturer and needs to be able to tell the user who that maker is.
An abstract property would be used where you want the class to always expose the property, but where you can't pin down the implemetation of that property - leaving it up to/forcing the inheriting class to do so.
There's an example here, where the abstract class is named Shape, and it exposes an abstract Area property. You can't implement the Area property in the base class, as the formula for area will change for each type of shape. All shapes have an area (of some sort), so all shapes should expose the property.
Your implementation itself looks just fine. Was trying to think of a sensible example of an abstract property for a Human, but couldn't think of anything reasonable.
I was reading about extension methods and how they can extend classes with new methods without having to change the class code definition.
I wanted to know if there was any similar way by which I can add a new data member (like a List or an array) to an existing class and use the data member to store information related to the class?
Yes you can extend that class using inheritence.
public class MyClass
{
...
}
public ExtendedClass: MyClass
{
public int ExtraField {get; set;}
}
This way you have all of the members and methods (except private) that exist on the base.
With extension methods you can only extend the functionality of a class.
What you are looking for can be solved with:
Aggregation OR
Inheritance
This post may help you on deciding which one to use in your case: Inheritance vs. Aggregation
There is no way of directly adding members to a specific class.
If the class isn't sealed, you may extend that class by using inheritance. If it is sealed, you may compose yourself a new class which encapsulates the specific class you wanted to extend and extend the implementation.
For example, if you have MyClass which isn't sealed and you want to extend it, simply inherit:
public class MyExtendedClass : MyClass
{
// Add extra logic
}
or, as for composing a new class yourself, you may do the following:
public class MyExtendedClass
{
private MyClass _class;
public string MyExtraString { get; set; }
}
You can use inheritance or composition for that.
Inheritance Example:
public class Student
{
int age;// all props
}
public class MAStudent : Student // MSStudent is a student with extra stuff.
{
float maAverage;
}
Composition Example:
public class Student
{
int age;// all props
}
public class MAStudent
{
Student student;
float maAverage;
// use student's functions inside the class
}
Inheritance is the easiest way to do things. The problem with it is that it makes your classes coupled.
The good perk with inheritance that you can access every protected+ property \ method.
Although the other answers seem to be correct, the answer to your question IMHO, is that it is not possible to extend an existing class with new properties in the way that extension methods do that. Once a class is defined, you cannot 'add' things to it.
Extension method is an exception, since that is just syntactic sugar for a static helper class.
Also you can write something based on extension methods like this
public class ExistingClass
{
}
public static class ExtendingExistingClass
{
private static Dictionary<ExistingClass,List> _values = new Dictionary<ExistingClass,List>();
public List GetMyNewField(this ExistingClass t)
{
List res = null;
_values.TryGetValue(t, out res);
return res;
}
public void SetMyNewField(this ExistingClass t, List value)
{
_values[t] = value;
}
}
Can I do something like this:
public abstract class DeletableEntity
{
[DataMember]
public bool Delete { get; set; }
}
[DataContract]
public class MyClass : DeletableEntity
{
[DataMember]
public int ID { get; set; }
}
I really only need DeletableEntity so others can inherit from it, so it doesn't need to go over WCF, can I send its Delete member with my MyClass without having to send the DeletableEntity as well?
No that should not be possible. From your requirements it would be simpler to use interfaces. Also, as an advise please consider using Known Types. This is not really directly related to you problem but it will allow you to use 'polymorphism' over wcf.
More details can be obtained here:
http://msdn.microsoft.com/en-us/magazine/gg598929.aspx
You have a couple of options with how the DataContractSerializer handles serialization:
Do nothing-- default behavior in .NET 4.0 and later is to send all
public members if NO declarations are made about [DataContract] or
[DataMember].
Declare DeletableEntity as a [DataContract] and declare the serializable [DataMembers]. Once you say something, WCF assumes you want to say more.
You'll probably want to do #2. Once you do that, add on a [KnownTypes] attribute if you have any WCF methods that take a DeletableEntity and it's derived types. You'll probably just want to use the string version of KnownTypes that passes a static method name. The static method can then use reflection on the assembly to pull out all types that derive from DeletableEntity such that the method catches any new items that are added as you code.
If you want the above, I recommend the following code:
[DataContract]
[KnownType("GetKnownTypes")]
public abstract class DeletableEntity
{
[DataMember]
public bool Delete { get; set; }
public static Type[] GetKnownTypes()
{
return (from type in typeof (DeletableEntity).Assembly.GetTypes()
where typeof (DeletableEntity).IsAssignableFrom(type)
select type).ToArray();
}
}
greetings. i have the following class:
public class Ship
{
public enum ValidShips
{
Minesweeper,
Cruiser,
Destroyer,
Submarine,
AircraftCarrier
}
public enum ShipOrientation
{
North,
East,
South,
West
}
public enum ShipStatus
{
Floating,
Destroyed
}
public ValidShips shipType { get; set; }
public ShipUnit[] shipUnit { get; set; }
public ShipOrientation shipOrientation { get; set; }
public ShipStatus shipStatus { get; set; }
public Ship(ValidShips ShipType, int unitLength)
{
shipStatus = ShipStatus.Floating;
shipType = ShipType;
shipUnit = new ShipUnit[unitLength];
for (int i = 0; i < unitLength; i++)
{
shipUnit[i] = new ShipUnit();
}
}
}
i would like to inherit this class like so:
public class ShipPlacementArray : Ship
{
}
this makes sense.
what i would like to know is how do i remove certain functionality of the base class?
for example:
public ShipUnit[] shipUnit { get; set; } // from base class
i would like it to be:
public ShipUnit[][] shipUnit { get; set; } // in the derived class
my question is how do i implement the code that hides the base class shipUnit completely?
otherwise i will end up with two shipUnit implementation in the derived class.
thank you for your time.
ShipPlacementArray deals with only one ship. but the array reflects the directions the ship can be placed at.
what i would like to know is how do i remove certain functionality of the base class?
You don't. This is not the point of inheritance. The point of inheritance is to inherit the base class functionality -- all of it -- and adding/changing stuff. It's for "is-a" relations, e.g., "a car is a vehicle."
my question is how do i implement the code that hides the base class shipUnit completely?
It sounds like you want ShipPlacementArray to be a wrapper, or container, of multiple Ship objects. This does not seem like a case where inheritance should be used.
Ask yourself the question: "is a ShipPlacementArray a kind of Ship?"
In my experience, every time I've wanted to remove a property from a class in an inherited class, my class design was flawed. One way to solve this problem would be to create a new base class without the ShipUnit property and then inherit that base class two times, once for your concrete Ship type and once for your concrete ShipPlacementArray type. In both subclasses you could implement ShipUnit as you need to.
You cannot make members of a base class disappear in a derived class. In certain instances, you can mask or hide the base members by using the new keyword on your hiding member in the derived class, but the user will always be able to cast your object back to the base class (base)instance_of_derived and access the base class's members.
So, for example, you can do in your derived class:
public new ShipUnit[][] shipUnit { get; set; }
But then I can do:
((Ship)ShipPlacementArray_instance).shipUnit
And this will reference the original shipUnit. Thus, you can "hide" the member but you cannot disable its functionality or accessibility.
With C#'s new modifier you can hide an inherited member from a base class member.
Check out this page for reference.
In additoin to the other excellent answers, as an aside I'd say you may find encapsulation to be a better option. Often I used to at first think I wanted to inherit from a class, and later found that I really wanted to encapsulate it. You do this by simply declaring a new instance of the original class in a private field. You then create public properties and function that simply call the original class like the below, giving you a fine grain of control over what gets exposed. This also is a way to side step the disadvantages of inheritance such as added complexity and inability to perform multiple inheritence(for good reason):
class SomeNew
{
private SomeOld someOld = new SomeOld();//could have done this in constructor instead
public DoSomething()
{
someOld.DoSomething();
}
}
I don't know if this is just a contrived example, or an actual problem. But, I would say that the inheritance in this case isn't desired. You have Ship and ShipPlacementArray. The "Array" at the end makes it sound more like its, well, an array data type. So taking that away, you have ShipPlacement.
That sounds to me like its a location somewhere, so maybe it should be a member of the Ship class?
"Favor object composition over class inheritance" - If you are looking for new behavior from the base class, then it doesn't seem like you'd want to inherit anyway because they are different types.
Perhaps Ship and ShipPlacementArray should inherit a common interface, but certainly not from a common base class. Anywhere you'd need to use either you could use the interface - but where you needed your ShipUnit matrix, you'd use the ShipPlacementArray type explicitly.
you can use the "new" operator.
as in
public new ShipUnit[][] shipUnit { get; set; } // in the derived class
You can use the new keyword, like this:
public new ShipUnit[][] shipUnit { get; set; }
I don't fully understand what you want to model with the inheritance but I am quite sure it is the wrong tool. I assume aggregation or composition are what you need.
you can use the new keyword or add virtual on the declaration on the base class and override it on the derived class.
I have 2 class's
Class 1.
public class BaseContentPage : System.Web.UI.Page
{
}
Class 2.
public class BaseUserControl : System.Web.UI.UserControl
{
}
And now i want them to be aware of this class.
public class BaseCommon
{
public string Variable1 { get; set; }
public string Variable2 { get; set; }
public string Variable3 { get; set; }
}
How I'm currently doing it is by making the variables of the BaseCommon class static like so
public static string Variable1 { get; set; }
public static string Variable2 { get; set; }
public static string Variable3 { get; set; }
How else can i do this?
Use composition.
Give BaseContentPage and BaseUserControl a private field (which can be exposed as a property if needed) of type BaseCommon (don't make it static).
They can either create BaseCommon or have an instance passed in through the constructor (Dependency Injection).
First off, I don't think you want the BaseCommon properties to be static. The properties are then global across the application so changing them from one instance will change them for all instances.
What you're talking about is multiple inheritence and it isn't supported by c#. You'd be better off changing BaseCommon to be an interface and having BaseContentPage and BaseUserControl implement that interface.
If they are static, does that mean that this third class is a global resource? You could look at Singleton or IoC containers or pass the instance to the other classes when constructed.
You need to give more concrete examples of what this common "base" data that you are adding to two different parts of your object inheritance tree are.
Conceivably, say each instance really just has similar data (an example I'm thinking of is internationalization, say, which is used to customize both a page and a usercontrol according to phrase IDs, etc which are specific in context), then what you can do is have a class I18nSettings which implements II18nSettings. Then in each class, encapsulate an I18nSettings instance and implement II18nSettings and pass them through. Alternatively, you can expose the internal I18nSettings instance. I've even just defined an interface and had each class implement it - it was not worth having a separate class at all.
There are other options to do this kind of thing - it depends on whether the concrete classes you are inheriting from implement a lot more useful things than the things you are adding. It might make more sense to inherit from your concrete class and implement other interfaces so that the class can be used in other places.