object reference vs an interface reference - c#

Difference between accessing an object’s methods with an object reference vs an interface reference, even if both refer (point) to the same object.
I dont know what is object
referene and interface reference please explain?

If you have a reference to an object using an interface, you will only have access to that objects methods or properties that are defined in the interface. If you need to access any additional methods, you have to identify the specific type of the implementation, and cast it to that type before calling those methods or properties.
Using the interface type instead of the actual type is often done to reduce coupling between objects. For example, one of your objects that are logging something might need an instance of ILogger, but it should not really care if the implementation of ILogger logs to a file, to a web-service or does something else. It should only care about getting an object that fullfills the contract that the interface defines.

If I understand you question correctly you are asking the difference between object of a class and object of an interface
Object of a class contains full implementation of the class. You will be able to call all the public methods and use public fields of that class through the class object.
On the other hand, interface object only exposes those methods and fields which are defined by interface.

One case is when you know the type of your object (so the class your object is an instance of) and this way you can access all its methods. Let me stress that again: you know the class of the object.
Second case is when you only know that your object implements an interface, you do not know which class your object is. This way you only have access to the methods that the class inherits from that particular interface, and no other method.

It's actually very simple. When you access object methods, with interface reference you can only access the methods that are part of that interface definition which are implemented by that object's class.
And when you access them with class reference then you can access all that are part of the class.
Actually with interface you don't care what is the actual class of that object, you only want to be concerned with the interface methods, that are implemented in that class, so you can access only those..

Related

Create new base class object from derived class object in C#

I've got an object of type Derived but want to have one of type Base. Normally, I can simply cast the object to a reference of Base. However, for my WCF service, I really want to expose the Base class only.
Is there a neat way to get the Base to a Derived object (or create a new Base from the Derived object) where the dynamic type is Base?
Example:
myWcfResult.PropertyOfTypeBase = objectOfTypeDerived; // do some magic in this line
Assert.Trace(myWcfResult.PropertyOfTypeBase.GetType() == typeof(Base)); // should hold afterwards
// or at least WCF should be able to serialize it correctly into an XML element of type Base
If what you are trying to achieve is to hide the extra properties of the Derived class, then there are two options
Either the consumer allows you to specify the type explicitly
Or you have to change your design.
In the second case you should consider using composition instead of inheritance e.g.
Wrap the Base or Derived objects into a new adapter class that will only expose the required properties
Have the Base class as it is, but instead of adding the extra functionality by deriving from it, use composition: the Base class would contain another object that would define some aspects of the behaviour.
It is difficult to help you without a concrete example I am afraid.
If nothing else comes up I'm going to accept my own hackaround as solution: using AutoMapper to clone the Derived into a new Base:
Mapper.CreateMap<Base,Base>();
Mapper.Map<Base,Base>(objectOfTypeDerived);

Passing an interface instead of an object instance

Take for instance the SqlBulkCopy.WriteToServer() method. One of the overloads takes an IDataReader as the parameter. My question is, what's the benefit/advantage to passing an interface to a method instead of the object instance itself?
http://msdn.microsoft.com/en-us/library/434atets.aspx
You can have many possible implementations for that one interface. Its better to depend on an abstraction (in this case an interface) than an actual concrete class - this allows much better flexibility and testability.
This also puts the focus on what is really required by the WriteToServer() method - the only thing its contract requires is for the caller to pass in any instance of a concrete class that provides the methods / properties declared by the IDataReader interface.
Passing an interface means that you can pass any object that implements that interface not just one particular object.
This makes the code more flexible as it doesn't have to know about all the possible objects that may implement the interface now or in the future.
It also makes it more robust as it only has to deal with the properties and methods on the interface which are well known and defined.
The formal parameter type is an interface type - that means that you can pass in any object that implements this interface (or rather, an instance of an object that implements the interface).
You are not passing in an interface, you are passing in an object that conforms to the contract defined by the interface.
So, if your data source is SQL Server, you would pass a SqlDataReader, if Oracle, an OracleDataReader.
You could also implement your own data reader and pass that to the function and even write a mock data reader to test the method thoroughly.
This is a well known design principle - Program to an Interface, not an implementation.
And from MSDN - When to Use Interfaces:
Interfaces are a powerful programming tool because they let you separate the definition of objects from their implementation.
When a method lists one of its arguments as an interface, it isn't requesting you to pass in an instance of that interface (which is impossible anyway, you can create instances of interfaces), it's asking you to pass in any object that implements that interface.
Example:
interface IMyObject {
public void SomeMethod();
}
public class MyObject : IMyObject {
public void SomeMethod() {
// implementing code here
}
}
You can now pass any instance of MyObject as an argument that is of type IMyObject :)
public class YourObject {
public void DoSomething(IMyObject o) {
// some code here
}
}
YourObject yo = new YourObject();
MyObject mo = new MyObject();
yo.DoSomething(mo); // works
I hope that makes sense!
Actually, it expects you to pass an instance of a type that implements the interface, rather than the interface itself.
The interface type is used when the only thing the method cares about are the methods declared by the interface. As long as the object implements that interface, methods defined in it can be invoked on the object.
This is one of the reasons for interfaces - in this example, all the consumer of the interface (i.e. the function) cares about is that it can read data - it doesn't mind whether it's from an SqlDataReader or an OleDataReader or for any other provider - the alternate would be providing separate overloads that are virtually identical for every possible Data Reader (which is of course impractical, given someone may come up with one for, say dBase or a more exotic database engine)

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

Force calling the derived class implementation within a generic function in C#?

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.

Class vs Interface

Recently I was asked in an interview that, can an Interface be considered as a class in C#? I.e. is an interface is a class in C#?
I was confused.
What can be the answer?
No, an interface is not a class.
An interface is a set of method signatures and possibly properties that all relate to a single idea. For example, the IList interface will have methods for indexing, inserting, and getting the number of elements. However, it does not define any implementation details. The list interface could be implemented as a linked list, or a wrapped up array, or anything you want, as long as it defines those methods in the interface.
A class is the template from which to create an actual object. Classes are a collection of method signatures, plus the implementations of those methods.
So no, an interface is not a class, as it merely defines a specific contract, while a class defines the whole behaviour of the object.
Commenter SquareCog accurately points out that the above is not entirely true. Since classes can be subclassed, and methods overridden, the class' relationship to the actual behaviour of an object gets somewhat more complicated. I'm just going to handwave that problem away by saying that classes are individual entities. You can read the source code for a class and know what behaviour that class encompasses. However, at runtime, objects have types instead of classes. Types are the entire inheritance tree, instead of a singular class, and thus a type's behaviour could be defined over several different classes. Luckily, this does not change the basic conceptual difference that interfaces are contracts that can imply (through names, argument types, etc) certain implementations, but cannot enforce anything but the method signatures, while classes do define an implementation, even if that is not the actual implementation used at runtime.
From a logical perspective, they are very similar. As noted by others, an ABC1 with only public abstract members would serve almost the same purpose as an interface.
When you get down to the nuts and bolts of it, the two have a number of important differences.
A class can only inherit from one base classes, but can implement many interfaces.
A value type, already deriving from ValueType, cannot inherit from an ABC, but can implement an interface.
A class can contain fields and static members. An interface cannot.
A class can contain implementation, an interface cannot.
A class can have private and protected members, an interface cannot.
Abstract members of an ABC are always virtual. A class can implement an interface with non-virtual members.
1: Abstract Base Class
Yes, any abstract class that contains no implementation and consists of abstract methods only would be equivalent to interface.
A Java interface is not a class; it is a declaration of methods that need to be implemented by classes; a description of abilities, if you will. Abstract classes in Java are an interesting half-way point between proper classes and interfaces, as they define the available methods, but also provide some default implementations.
The fundamental difference between an abstract class and an interface in Java is that you can only extend one class; you can implement multiple interfaces. An abstract class describes what you are; an interface describes what you can do. What you are also defines what you can do -- but it has significantly stronger meaning.
In general, an Interface is a type that can be implemented by a class to indicate that the class exposes a behavior through a set of methods. For example, .Net has an ICollection interface that contains methods to interact with a collection.
In C++, an interface is a class where every method is abstract.
In Java and .Net, interfaces are independent types that are unrelated to classes.
Either way, classes can implement interfaces.
There could be several answers.
No, a class is not an interface - an interface defines a contract, a class is a type of object which can be created.
Yes, an interface can be viewed as a base class with only virtual methods - this is how interfaces are defined in C++.
It's helpful to regard .net as having three "safe" kinds of types in .net: interfaces, classes, and value-types (there are also things like pointers and such, but those are another story), and three main contexts classes may be used: storage locations, heap objects, and generic constraints.
Heap objects may be of any type, but all heap objects behave like class objects. Heap objects of interface type are rare; they are not generally created within .net but may be created by code designed to work with older object models. Heap objects of class types contain one storage location for each field; heap objects of value types contain one storage location whose type is the value type in question.
Storage locations may likewise be of any type, but value-type storage locations differ from the others. A storage location of class type or interface type holds a class reference. A value-type storage location contains either a value primitive (byte, integer, char, floating-point number, etc.) or else contains a storage location for each field of the value type (so, e.g., a storage location of type Point holds two storage locations of type Int32, each of which holds a signed-32-bit-integer primitive).
Generic constraints may also be of any type, but constraints of interface types do not confine the constrained generic type parameter itself as being a class type, interface type, or value type. A method declared void Foo<T>(T param) where T:IWowzo could be called with a parameter of class type, interface type, or value type. If the routine is called with a value-type parameter, then param and any other storage locations declared to be of type T will be stored as value types. If the routine is called with a parameter of class type or integer type, then param and any other storage locations declared to be of type T will be stored as class references. It's important to note that if T is itself an interface type (IWozo or a derivative) then param will be passed as a reference to a heap object, and will behave like one regardless of whether the type of the object instance is a class object or value type. If struct Bar implements IWowzo, and myBar is a variable of type Bar, calling Foo<Bar>(myBar) may yield different semantics from Foo<IWowzo>(myBar); in the former case, the parameter will behave as a value type and in the latter case it will behave as a class type.

Categories

Resources