Why can't variables or fields be declared in interface + c# - c#

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.

Related

How Can I have abstract parameters in method?

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.

What's the use of declaring an interface as a class member?

I cant really understand what happens and what's the use of declaring a class member as an interface. MSDN says that interface cannot be instantiated, so you can't say:
IMovable i = new IMovable();
The reason you can't do this is pretty straight forward. But what's the use of declaring, for example:
protected static IMovable i;
What does i represent in this case? What's the use of it?
Thanks
Because you will write your code so that it can use any implementation of IMovable, rather than just that one.
This allows you to build loosely coupled code.
You want to store a reference to an object implementing that interface, but you don't care what kind of object it is, only that it implements that interface.
The member i can represent any object the implements IMovable, that's why it's useful. You can assign different objects to i and have specific behavior depending on the object.
That interface member will be assigned to an instance of a class implementing the interface by someone - either a DI framework or by custom code. Otherwise, yes, would be no point.
Interface is kind of Abstraction (Contract) and cannot be instantiate. But if you implement your in your class then your:
interface IMovable {
void DoStuff();
}
class ImplementinIMovableClass : IMovable {
void DoStuff() { .. }
}
protected static IMovable i = new ImplementinIMovableClass();
Variable i only has property/method defined in that interface. In that case it is method DoStuff();
With Interface approach you can think of use DependencyInjection to reduce your code cupling.
As many other answers have already pointed out, the i member variable can point to any implementation of IMovable.
This is not only a great benefit in terms of flexibility, but it is one way to realize the OO principle of Polymorphism.
Thomas
Interfaces and abstract classes are very similar, though abstract classes may be easier to understand in the real world.
Something like "vehicle" would be an abstract class; something like "2010 Toyota Prius Hatchback" would be a concrete class. It is possible to have, or to drive, either of the above. On the other hand, one wouldn't buy a "vehicle" as such--one would buy a particular type of vehicle. In real life, a person might hypothetically ask someone to buy him a vehicle, without specifying any particular kind, but in most programming languages a compiler in such a situation would want to know what sort.
The code which actually creates an object will have to know what type of object it's creating, but in many cases code will be given objects which have been created by other code. Code which uses an abstract class or interface to specify what it's expecting from other code will be usable with other code that creates any class which derives from that abstract class or implements that interface.

Why must the base class be specified before interfaces when declaring a derived class?

public interface ITest
{
int ChildCount { get; set; }
}
public class Test
{
}
public class OrderPool : ITest, Test
{
public int ChildCount
{
get;
set;
}
}
The error says Base class 'Test' must come before any interfaces.
Why is it necessary to extend the class first and then implement the inteface?
Because the specification says so in section ยง17.1.2.
C# supports only single inheritance, but allows classes to implement multiple interfaces. That being the case, it's much clearer to always have the base class specified in the same place by convention, rather than mixed in with a bunch of interfaces.
Regardless of convention, the specification mandates that this is the case anyway, which is why you're seeing that error.
Remember, there's nothing in the specification that says all of your interfaces have to be named with a capital "I". - that's just convention. So if your class implemented interfaces that didn't follow that convention, and if the specification allowed you to specify the base class and interfaces in any order, you wouldn't be able to easily tell which identifier was the base class and which were interfaces. Example:
class MyDerivedClass : A, B, C, D, E // which is the base class?
{
...
}
it's called syntax
There are conventions that you must follow in order for the compiler to compile the code.
They could have chosen to allow both forms, or just the other way around, but they didn't.
The reason is probably clarity : you can define a lot of interfaces and only inherit from one class.
Technically it would have been possible to allow them all in random order, but that would make the code less readable.
Simply because the language is designed like that. The reason is probably that a class can have only one base class, but implement any number of interfaces.
Because you can extend just one class and implements more than one interface, having the class first make easier to read. And probably the grammar itself is easyer to write that way, just a pseudo grammar could be:
class CLASSNAME:baseclass? interface*
meaning optional baseclass followed by many interface, writing one grammar that allow just one class messed somewhere would be difficult without any reason.
You can only inherit from one base class but many interfaces. So if there is more than one type listed you know that the first one is a class, the others interfaces. This works regardless of class/interface naming conventions
The order makes clear sense, the base class can implement members of the interface for the derived class, therefore the compiler must know of them beforehand

Implementing an Interface but changing a member to be private

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...

C# class design - what can I use instead of "static abstract"?

I want to do the following
public abstract class MyAbstractClass
{
public static abstract int MagicId
{
get;
}
public static void DoSomeMagic()
{
// Need to get the MagicId value defined in the concrete implementation
}
}
public class MyConcreteClass : MyAbstractClass
{
public static override int MagicId
{
get { return 123; }
}
}
However I can't because you can't have static abstract members.
I understand why I can't do this - any recommendations for a design that will achieve much the same result?
(For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes, there are good reasons for keeping it static.)
You fundamentally can't make DoSomeMagic() work with the current design. A call to MyConcreteClass.DoSomeMagic in source code will be translated into MyAbstractClasss.DoSomeMagic in the IL. The fact that it was originally called using MyConcreteClass is lost.
You might consider having a parallel class hierarchy which has the same methods but virtual - then associate each instance of the original class with an instance of the class containing the previously-static members... and there should probably only be one instance of each of those.
Would the Singleton pattern work perhaps? A link to the MSDN article describing how to implement a singleton in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In your particular example, the Singelton instance could extend an abstract base class with your MagicId in it.
Just a thought :)
I would question that there are "good reasons" for making the abstract members static.
If your thinking is that these members might reflect some property of the derived class itself rather than a given instance, this does not necessarily mean the members should be static.
Consider the IList.IsFixedSize property. This is really a property of the kind of IList, not any particular instance (i.e., any T[] is going to be fixed size; it will not vary from one T[] to another). But still it should be an instance member. Why? Because since multiple types may implement IList, it will vary from one IList to another.
Consider some code that takes any MyAbstractClass (from your example). If this code is designed properly, in most cases, it should not care which derived class it is actually dealing with. What matters is whatever MyAbstractClass exposes. If you make some abstract members static, basically the only way to access them would be like this:
int magicId;
if (concreteObject is MyConcreteClass) {
magicId = MyConcreteClass.MagicId;
} else if (concreteObject is MyOtherConcreteClass) {
magicId = MyOtherConcreteClass.MagicId;
}
Why such a mess? This is much better, right?
int magicId = concreteObject.MagicId;
But perhaps you have other good reasons that haven't occurred to me.
Your best option is to use an interface with MagicId only using a setter
public interface IMagic
{
int MagicId { get; }
}
By the nature of Static meaning there can only be one (yes like Highlander) you can't override them.
Using an interface assumes your client will implement the contract. If they want to have an instance for each or return the value of a Static variable it is up to them.
The good reason for keeping things static would also mean you do NOT need to have it overridden in the child class.
Not a huge fan of this option but...
You could declare the property static, not abstract, virtual and throw a NotImplementedException which returns an error message that the method has to be overridden in a derived class.
You move the error from compile time to run time though which is kinda ugly.
Languages that implement inheritance of static members do it through metaclasses (that is, classes are also objects, and these objects have a metaclass, and static inheritance exists through it). You can vaguely transpose that to the factory pattern: one class has the magic member and can create objects of the second class.
That, or use reflection. But you can't ensure at compile-time that a derived class implements statically a certain property.
Why not just make it a non-static member?
Sounds like a Monostate, perhaps? http://c2.com/cgi/wiki?MonostatePattern
The provider pattern, used by the ASP.NET membership provider, for example, might be what you're looking for.
You cannot have polymorphic behavior on static members, so you'll have a static class whose members delegate to an interface (or abstract class) field that will encapsulate the polymorphic behaviors.

Categories

Resources