Basiclly I have a class like Individual and another class that inherits from it - IndividualForSomeAnotherWork.
I have a class called Population too and methods like Add(Individual individual).
Can I pass the IndividualForSomeAnotherWork to Add method through Individual type? Or should I use interface or abstract class? I'm asking because I'm getting NullReferenceException all the time.
EDIT:
Sorry for not answering so long. My problem was not initializing a List containing objects so I couldn't add to it. But I also wanted to know that can I pass arguments as I said earlier. Thanks for answers.
I would recommend an IIndividual type of interface. In this case, if you have:
abstract class Individual : IIndividual {
}
class IndividualForSomeOtherWork : Individual {
}
... then Population.Add(IIndividual Individual) will accept the base class Individual as well as any descendants of Individual.
Think of the interface as a contract with the Population class that any individual within it's collection will have implemented all the functions it requires of the individual.
Note that the abstract Individual is not required to implement all functions defined within the interface. If the interface requires:
interface IIndividual {
void DoWork();
}
... then the base Individual is not knowledgeable of what specialized work an IndividualForSomeOtherWork will actually perform. So in the abstract class:
abstract void DoWork();
This function must be defined within the specialized individual descendants.
Yes, you can pass an IndividualForSomeAnotherWork to Add(Individual individual). It should work correctly. Your error is due to something else. Try debugging it yourself, or post more details and code and we might be able to help.
In terms of what you are trying to do here, an abstract class is not fundamentally different from an interface. In both cases it's not possible to have a argument whose type exactly matches the type of the formal parameter. See DrawImage for an explicit example of this (Image is an abstract class).
The NullReferenceException you are seeing is not directly related to the parameter type being abstract.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
am familiar with abstract classes, interfaces, and the like.
What is not clear to me is why anyone would create a C# abstract class that does not have abstract members?
(the C# compiler allows this).
Example:
public abstract class House
{
public void OpenDoor()
{
Console.WriteLine("Door opens");
}
}
You may need a common base to access to refer to so you can process a list of many different types of houses. You could have a List<House> and some of those could be BrickHouse others WoodenHouse but opening the door functions the same for all houses so it makes sense to put the method in the base. You declare the base abstract if it does not make sense to instantiate that class.
simply because: you are expected to subclass it?
Maybe in this context, House simply isn't specific enough; sure, all things in this relationship are houses, but it is expecting concrete types such as Bungalow, Mansion, Apartment, etc... So House serves as a useful categorisation (for example, in a List<House> or a property of type House) - but you would never expect to have an actual instance of that common base type.
I could imagine that some platform (perhaps in a company) might define an abstract class programmers should subclass so that methods can be added in later versions?
Just to auto implement things for them, so for example provide a default implementation of GetHashCode, or maybe ToString. Also, it allows for you to add a method to an interface that the abstract class implements, provide a default implementation, and then nothing breaks, instead of the other option where every class breaks and you have to fix all of them manually.
Interestingly, static classes in C# are in fact sealed and abstract ones. The purpose in this very case is clear: allowing to declare static methods only.
So that the base class defines the implementation. If the Implementation is common across all the derived classes it makes sense to keep it in the abstract class not duplicate the code in the derived class.
See this link, has some useful info about this
http://www.codeproject.com/Articles/6118/All-about-abstract-classes
abstract classes, at all, are more of a logic class to inherit from rather than use it as basic for inheritance, you can use abstract class to tell all who inherits from it to have a certain property or a specific method to do,
Interfaces can do exactly that.
Lets say I have a mammal class, but a mammal class is just an abstract class, there is no real animal that is of a kind of a mammal, although there are many animals ( including humans) that inherit "properties" from it.
Again, abstract use is definitely up for the developer choice.
Abstract classes with abstract members are meant to be used polymorphically. Abstract classes with only concrete members would be used if you wanted to share common methods with subclasses, perhaps even a specific construction sequence (as in having the abstract class's constructor do setup that's "housekeeping").
It's a weaker form of coupling than polymorphic subclasses, and I can't think of a time I've run across it myself.
Abstract class serves as a template (may or may not provide default implementations) while child could overwrite anything he does not like, or additional methods/properties/etc.
a very interesting scenario is type constraint inheritance:
public abstract class MyClass
{
public void DoSomething()
{
Console.WriteLine("blah blah");
}
}
public class MyClass<T>: MyClass
{
public T GetSomething()
{
// return null as T;
}
}
you may see the default implementation is at the base class.
Generalization
Abstract classes can be a conceptual 'Interface'. This is different from a .NET interface.
A generalized interface example is:
// List that accepts the conceptual interface
List<Car> cars = new List<Car>();
// Specialized instance that will be added to the list
Car myCar = new Toyota();
cars.Add(myCar);
Inheritance
You can implement multiple interfaces but inherit just from one abstract class. This can be a design decision made by the developer of the class library.
Usage
Dhananjay wrote a nice post about the usage. He states that abstract classes are used for modelling your class hierarchy. Interfaces however are used for communication. That the object actually is does not matter.
Often the base class is used to provide just common functionality. Depending on your design this common functionality can be implemented without dependencies on members. In this case usually the subclasses don't need any common members. In you example the House class of objects is used for simple actions and I assume you don't need any common state of the house such as number of floors, type of walls (wood, bricks, etc.). Seeing such a class makes me think "OK, this class isn't holding any state of the object. It just performs some action"
I know the the concept of interface and implementation of it also
I know properties and method definitions can be written interface .
But while going through topics related i came to know that we cant declare a variable in interface . Just wanted to know the reason for it ?
Because variables and fields are the implementation. Interfaces are contracts that declare what they do, not how they do it.
If you want to declare fields, then you need to create a base (possibly abstract) class.
From consumer point of view, an important difference between an interface an an abstract base class is that you can derive your class from only one base class while your class may implement as many interfaces as you want.
Lets say that it can be defined. So:
interface Foo
{
int Number;
string Text;
}
class Bar : Foo
{
public int Number;
public string Text;
}
So, in each derived class (class that implements Foo interface) you would have to create two public members. That, at least to me, makes no sense.
If you want your classes to have some members that are not methods, and you would like to simplify it as much as possible, take a look at Auto-Implemented Properties.
Interfaces are intended to describe behavior, not implementation.
Because a variable defines how things are stored inside your object. This is not compatible with the idea of an interface.
Besides it would lead to multiple-inheritance-style problems like
interface A { int x; }
interface B { int x; }
class C : A, B
Which instance of x should be included in C (one och both and how do you differ them in that case?)
You should use a property in your interface as that can be defined with out specifying the implementation. That serves the same purpose but with better encapsulation.
Beyond "because that's the spec" I'm not sure, one reason might be that it seems to me that everything allowed in an interface can be tied directly to a method ( Properties map one or to two methods ).
Whats the use of an interface? Its basically acts as contract. So whats the point of having a predefined format of a variable declared in ur contract? No use. Plus its like a template.
The idea of an interface is to declare the parts of a type accissible to the outside world or reversely not to care about implementation details. Since fields should be regarded as implementation details it would be a contradiction even to be able to declare them
Interface acts as a contract. So, it can't contain the variable declaration. However, it may contain Properties declation, that you will implement in the inherited class.
I have some user controls which I want to specify properties and methods for.
They inherit from a base class, because they all have properties such as "Foo" and "Bar", and the reason I used a base class is so that I dont have to manually implement all of these properties in each derived class.
However, I want to have a method that is only in the derived classes, not in the base class, as the base class doesn't know how to "do" the method, so I am thinking of using an interface for this. If i put it in the base class, I have to define some body to return a value (which would be invalid), and always make sure that the overriding method is not calling the base. method
Is the right way to go about this to use both the base class and an interface to expose the method? It seems very round-about, but every way i think about doing it seems wrong...
Let me know if the question is not clear, it's probably a dumb question but I want to do this right.
EDIT : Thanks to all the people with your excellent abstract suggestions, but this breaks the designer. If abstract was not a selectable option, what would you do?
Alternatively you could define the method as 'abstract' in the base class, which will not require the class to implement it. For example:
abstract class A
{
public abstract void B();
}
Of course this will force your base class to be abstract as well, but it sounds like this would work just fine for you.
See Abstract methods on MSDN.
Update
Since abstract is not an option for you due to designer issues, you could just define the method as part of your base class, and have it throw a NotImplementedException if it is called directly from the base class:
void DerivMethod()
{
// Must be implemented by derived class
throw new NotImplementedException();
}
Otherwise, using an interface would be fine, especially if the above leaves a bad taste in your mouth...
You should make your base class an Abstract class. Then the base class can implement the Interface by marking the method abstract.
http://msdn.microsoft.com/en-us/library/aa664435(VS.71).aspx
Mark the method as abstract in your base class. You'll be forced to implement it in the derived classes, but the base class will not need to have a method definition.
I agree with with others, but making your user control abstract has some issues for the designer. The designer will often not display the abstract user control.
I would implement the interface methods in the base class. You can throw a NotImplemented exception or Assert.Fail in the methods if you want to make sure the inheritors are overriding these methods properly.
Declare the function signature in the base class and use the "abstract" modifier.
All members of an Interface are public by default. But there are some properties in my interface that I want to be used as private members of some subclasses that implement my interface. Is this something that can and is done or am I way off basis here. I'm working on using more Interfaces in my architecture these days so I'm not that well versed yet.
The point of interfaces is that they provide a contract that other objects can use to communicate with your object. If you change a member which is declared as public in an interface to private then you're not fulfilling the contract - another object may need to read that property / call that method, and you must allow them to.
An interface will never have private members as an interface is for "interfacing" between two objects. Your internal private members don't matter to it as long as you hold up your end of the contract.
Going on your question, and your use of the word "subclass", I don't think you've fully understood Interfaces yet.
I know you've probably heard this a million times but, an Interface describes what an object DOES, and a Class is HOW it does it. A Class IMPLEMENTS, an interface, it does not INHERIT from it.
So, if you want, have an Interface for you base Class, or for your SubClasses, but your question makes me think you're thinking about a base Class (Abstract Class), not an Interface.
Does that make sense?
As interface does not has an Access Modifier, if you still want your method private in the class which is implementing that interface, you can Implement that interface EXPLICITLY.
In that way your class methods will be Private.
You have to fully understand what interfaces are. In fact there are just descriptions of the expectations that outside world could have about the class members. It do not creates the member, it just informs that specified class have specified method to use in public scope. So, as you can see by interface you could only describe public members.
On the other hand if you want to declare some private members that are fixed or virtual you can use classic inheritance with the abstract base class. In this case you will make all methods that you want to implement in subclasses as abstract, and implement methods that you want to be defined in base class.
Hope this helps.. Regards
Interfaces are only good for public access. Internally, it would be strange for an object to refer to itself through an interface.
If you want to have private variables that you force an implementation of, you want to use an abstract class, and mark them as protected.
Think a little about this - and you understand that this can not be done:
Interfaces are like a contact. all the public fields of the interface are parts of the contact.
So, you can't hide them in a subclass... What would happen if someone were to upcast your class object to the interface's type ?
You'd probably want to change your design - may be split your interface in to two interfaces?
or and interface and an abstract class? we need more details to know...
Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead.
Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use.
For ease of understanding I've created a small example as follows:
class StandardBaseClass {} // These are simulating the SMO objects
class StandardDerivedClass : StandardBaseClass {
public object Parent { get; set; }
}
static class Extensions
{
public static object GetParent(this StandardDerivedClass sdc) {
return sdc.Parent;
}
public static object GetParent(this StandardBaseClass sbc)
{
throw new NotImplementedException("StandardBaseClass does not contain a property Parent");
}
// This is the Generic function I'm trying to write and need the Parent property.
public static void DoSomething<T>(T foo) where T : StandardBaseClass
{
object Parent = ((T)foo).GetParent();
}
}
In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass.
This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation.
I see this behaviour as a bug. Has anyone else out there encountered this?
I see this behaviour as a bug.
This behavior is correct. Since your method DoSomething is constraining T to StandardBaseClass, you only have access to the specific methods of StandardBaseClass, not any methods or properties of a derived class. Since StandardBaseClass does not have a Parent property, this is invalid, and should be invalid, by design.
There are two potential options here - You can use reflection to pull out the Parent property, or use C# 4's dynamic type, and treat this as a dynamic object. Both bypass the standard type checking in the compiler, however, so will require you to do extra type checking at runtime to verify that the Parent property exists.
Create an interface that contains the Parent property. Have each class that has a Parent property implement that interace. You will then be able to create a generic method that accepts a parameter of type IHaveParent, and it will do the right thing.
For anyone that is interested an succinct answer to this situation is answered by Stephen Cleary on msdn here:
http://social.msdn.microsoft.com/Forums/en-AU/csharpgeneral/thread/95833bb3-fbe1-4ec9-8b04-3e05165e20f8?prof=required
To me this is a divergence in the class hierarchy. By this this I mean that either the base class has parent, or the derived classes with Parent are derived from an abstract child of the base.
Lol as John says, an interface as opposed to an abstract class is sufficient too.
You idea won't work because the compiler can never guarantee that the base class actually would have such a property. And it won't just select the "right" one based on if it has it or not.
The only way you can do this is using reflection and then test at runtime if the requested property exists on the inspected class. You have to judge yourself if that is a viable way to do for your project (reflection is slow and requires maximum rights).
This is correct, as the compiler only knows that it can bind to your type as a StandardBaseClass. The binding is not done at runtime (where it could potentially decide to use the StandardDerivedClass overload.
If you know that it's a StandardDerivedClass, then why not just cast it as such?
object Parent = ((StandardDerivedClass)foo).Parent;
It's a bit ugly, but you can accomplish this using a Registration system, where you register delegates for different possible derived classes that expose the 'shared' property/method and then use something like a Dictionary<Type,Func<SomeT>> to store the delegates. If you know all of the derived types ahead of time and don't have to load plug-ins or the like, you can also use the classic ugly if/else-if structure. Either way you're basically creating your own substitute for what should have been supported by the virtual method table.