I'm creating a modular type system were one application(host) loads other modules in to a common UI interface, I have also created an API for this and is available for other users to use.
The API in some instances uses interfaces and abstract classes to force the client using the API to implement the specific methods.
I cannot use interfaces for everything as there are some things were I require putting in my own body so the end user does not need to implement all the unnecessary events and methods himself. EG: So I handle the size changing events myself then pass him the size to a function he implements from called SizeChanged were he can handle his program from the size change.
Abstract classes are what I really want to use but I cannot because the controls the user has may need the x:Name specified in XAML and will recieve the error:
The type ... cannot have a Name attribute. Values types and types without a default constructor can be used as items within ResourceDictionary.
The error occurs because an instance of it needs to be created:
Inherited Window can not have a name?
The only solution available to me that I know of is to use a regular class with virtual methods that can be overridden and that does work fine but it does not force the user to implement my methods that are required.
Is there anything I can do cleanly such as any public implementable or something?
This is the structure:
API:
IContext -> ContextControl -> (Abstract methods)
Module DLL
ContextControl(API) -> AppContextControl(Override methods)
Host Application pull's AppContextControl
I know I can tell the module dev to implement an interface as well as this ContextControl that constrains them to implement the interfaces but it would be much more professional for the compiler to tell them.
In the dev module if I instead of inheriting from ContextControl I implement IContext then I lose all the default bodys and the module dev gotta implement a lot lot more.
Cheers.
The two ways you've described - interfaces and abstract classes - are (as I'm sure you know) the recommended ways to do what you're describing, at least, if you want to enforce the implementation at compile-time.
The only other way I'm aware of is to provide a default implementation that throws a NotImplementedException(). That'll give you a run-time error, but nothing at compile-time, unfortunately.
This may or may not be applicable in your specific situation, but another possible way to get around your limitation is to use a Strategy pattern.
Instead of having the user override members, have them pass in parameters containing the functionality to the constructor. This could either be as delegates or as specific classes you create for the purpose.
Can't you use a combination of inheritance and interfaces? In other words, create virtual methods for the methods that can be overridden and use interfaces to implement methods that must be overridden?
I recently have a similar problem (dnt know it will help in your case). where i have to generate errors at compile time instead of Runtime, with generic functionality. the approach i used was combination of Generics and Interfaces. Examples are...
1) Enum Ex:(C# String enums)
Problem was to set things so that i dnt have to implement every code throughout the project and force Constructor.
public abstract class EnumEx<T> where T : EnumEx<T>
{
private readonly string _displayValue;
private readonly string _value;
protected static ReadOnlyCollection<T> EnumExs;
protected EnumEx(string displayValue, string value)
{
_displayValue = displayValue;
_value = value;
}
public string DisplayValue
{
get { return _displayValue; }
}
public static T FromString(string option)
{
foreach (var enumEx in EnumExs.Where(enumEx => enumEx._value == option))
{
return enumEx;
}
Debug.WriteLine(string.Format("Exception in EnumEX FromString({0})", option));
return null;
}
public override string ToString()
{
return _value ?? string.Empty;
}
}
2) Deep Copy(Generic method to create deep copy of all elements in a collection) + Editable Implementation IEditableObject over custom List
public abstract class CloneAbleBase<T> : ObservableObjectEx, ICloneable, IEditableObject
where T : DataBase<T>, new()
{
protected T CurrentData = new T();
private T _backupData;
private bool _isInEditMode;
public object Clone()
{
var dataObject = (CloneAbleBase<T>) MemberwiseClone();
dataObject.CurrentData = CurrentData.Copy();
return dataObject;
}
public void BeginEdit()
{
if (_isInEditMode) return;
_backupData = CurrentData.Copy();
_isInEditMode = true;
}
public void EndEdit()
{
if (!_isInEditMode) return;
_backupData = default(T);
_isInEditMode = false;
RaisePropertyChanged(string.Empty);
}
public void CancelEdit()
{
if (!_isInEditMode) return;
CurrentData = _backupData;
RaisePropertyChanged(string.Empty);
}
}
In similar way you can create base class for your Window or any control, where you need functionality some sort of generic functionality..
An alternative i can see in your very specific situation is to use interfaces (which, as you said, won't let you inject your own code) and then inherit from the actual type the end user provides and passed in as an interface and inject your own code there at runtime
For example you load all classes implementing IMyPlugin defined as such
public interface IMyPlugin{
void MyEndUserMethod();
void YourMethod();
}
User implements a class that inherits from it
public class UserClass:IMyPlugin{
....
}
You want to force your own code instead of YourMethod, then generate a class at runtime that inherits from UserClass and in YourMethod create your own code and call (or not, depending on your need) base on it. Call base on all other method where the user is to provide the implementation.
This is a bit more work for you but it hides all the uglyness from the end user, simply forcing him to implement the interface. For less uglyness make that interface into 2 interface
public interface IPlugin : IUserPlugin,ICreatorPlugin
And be clear to your users that while the classes must implement IPlugin anything from ICreatorPlugin can be left empty.
An even better solution would be to only expose IUserPlugin and do even more work on your side (your runtime class inherits from the user class AND ICreatorPlugin, and then use duck typing to make it into IPlugin).
Related
What are the differences in implementing interfaces implicitly and explicitly in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.
Here's an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.
Reason #1
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Reason #2
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
The class's primary interface, which is used by web page developers; and
A "hidden" interface used by the presenter that I develop to handle the control's logic
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
But's It's Not a Silver Cannonball
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to
understand some ramifications that
exist when using EIMIs. And because of
these ramifications, you should try to
avoid EIMIs as much as possible.
Fortunately, generic interfaces help
you avoid EIMIs quite a bit. But there
may still be times when you will need
to use them (such as implementing two
interface methods with the same name
and signature). Here are the big
problems with EIMIs:
There is no documentation explaining how a type specifically
implements an EIMI method, and there
is no Microsoft Visual Studio
IntelliSense support.
Value type instances are boxed when cast to an interface.
An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
When required, as per disambiguation or needing an internal interface
Discourages "programming to an implementation" (Reason 1 by Jon)
Problems
It's not all fun and happiness. There are some cases where I stick with implicits:
Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
(My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).
In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
This code compiles and runs OK, but the Title property is shared.
Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.
Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.
If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.
Public Overridable Function Foo() As Integer Implements IFoo.Foo
Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
Not as nice.
The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.
// Given:
internal interface I { void M(); }
// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }
// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }
The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.
Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
I've found myself using explicit implementations more often recently, for the following practical reasons:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways
Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI
No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too
Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync
I am working on a C# project that sits on top of a 3rd party CMS. The team is leveraging Dependency Injection to promote loose coupling between classes.
I have the need to "extend" the apis of the CMS with common functions that are used in several pages.
What makes it interesting is these common functions have multiple dependencies.
In this case, is it more appropriate to extend this functionality using static extension methods or by creating new interfaces?
Context
Let's say the 3rd Party has two interfaces IContentLoader and IPageSecurity that work with Page objects:
namespace 3rdParty.Api
{
public class Page{}
public interface IContentLoader{
T LoadItem<T>(Guid id) where T : Page;
}
public interface IPageSecurity
{
bool CurrentUserCanReadPage(Page p);
}
}
And I want to write a common method like:
public IEnumerable<T> LoadAllChildPagesTheUserCanRead(Guid id) where T:Page
{
//load page, recursively collect children, then
//filter on permissions
}
(I admit this example is a bit trite)
Extension Methods
I could create a static extension method using Property Injection:
public static class IContentLoaderExtensions
{
public static Injected<IPageSecurity> PageSecurity {get;set;}
public static IEnumerable<T> LoadAllChildItems(
this IContentLoader contentLoader, Guid id){}
}
This method is then very discoverable, we use IContentLoader often so it's easier for a team member to find it. However, I have read that Property Injection is generally less beneficial than Constructor Injection and should be avoided if possible.
Wrapper
On the other hand, I could create a Wrapper:
public class AdvancedContentLoader
{
public AdvancedContentLoader(IContentLoader c, IPageSecurity p){
//save to backing fields
}
IEnumerable<T> LoadAllChildItems(Guid id){}
}
This approach allows for Constructor Injection, which avoids the potential hazards of Property Injection, but makes the method less discoverable. The consumer would need to know to depend on AdvancedContentLoader instead of using the IContentLoader they are use to.
Summary
In this case where a method has multiple dependencies, is it better to promote discoverability by using an extension method and take whatever brittleness may come from using Property Injection? Or is Construction Injection so favorable that I should create a wrapper class at the cost of making the method harder to find?
I would lean more towards the wrapper class but I would create another interface for it. I would name it similar so developers can find it.
public interface IContentLoaderWithPageSecurity : IContentLoader
{
IEnumerable<T> LoadAllChildItems<T>(IContentLoader contentLoader, Guid id) { }
}
New interface but same starting name so intellisense can help developers. Also this interface has to implement the 3rd party interface.
I would change your AdvancedContentLoader class to implement this interface and chain all calls to IContextLoader to 3rd party implementation and handle just the specific methods it needs to handle.
public class AdvancedContentLoader : IContentLoaderWithPageSecurity
{
private readonly IContentLoader _internalContentLoader;
private IPageSecurity _pageSecurity;
public AdvancedContentLoader(IContentLoader contentLoader, IPageSecurity pageSecurity)
{
_internalContentLoader = contentLoader;
_pageSecurity = pageSecurity;
}
// Chain calls on the interface to internal content loader
public T LoadItem<T>(Guid id) where T : Page
{
return _internalContentLoader.LoadItem<T>(id);
}
public IEnumerable<T> LoadAllChildItems<T>(IContentLoader contentLoader, Guid id)
{
// do whatever you need to do here
yield break;
}
}
The benefits of this is if you are using DI Container you can just register IContentLoaderWithPageSecurity interface to the class and you are still coding to an interface.
The naming convention helps the developers find it with intellisense, if the namespace of the class is in the using directive.
The new interface implements the old one so existing code base that needs IContentLoader you can still pass down IContentLoaderWithPageSecurity into those methods.
I would only lean towards extension methods if I didn't require a new dependency and could just just what is already there - otherwise you have to get "smart" and do property injection or something like the ConditionalWeakTable to hold extra state for the class.
I agree with Wiktor Zychla that this starts to become peoples subjective opinions.
I suggest a decorated content loader. This approach follows SRP principle, where you don't mix responsiblities - I still have a content loader and when I want to implemenet loading multiple elements, I delegate this to another class.
public class DecoratedContentLoader : IContentLoader
{
IContentLoader c;
IPageSecurity p;
public DecoratedContentLoader(IContentLoader c, IPageSecurity p)
{
this.c = c;
this.p = p;
}
public T LoadItem<T>(Guid id) where T : Page
{
var page = c.LoadItem<T>( id );
if ( p.CanUserReadPage( p ) )
return p;
// throw or return null
}
}
As you can see, this uses the security provider but still implements a single item provider interface.
Thus, another class responsible for loading multiple items can just take IContentProvider as an argument and use either the bare one or the decorated one without distinguishing between the two.
public class AdvancedContentLoader
{
// no need for additionak parameters, works
// with any loader, including the decorated one
public AdvancedContentLoader( IContentLoader c )
{
//save to backing fields
}
IEnumerable<T> LoadAllChildItems(Guid id){}
}
So, my initial reaction to this is that there might be a bit of over-thinking going on here. If I understand your question correctly, you are trying to figure out the easiest way to extend a third party API. In this case, the API has an interface that you like, IContentLoader, and your goal is to add another method to this interface which enables it:
in addition to loading a given page (defined by Guid),
to recursively load all child pages as well,
so long as the user has permission (which is in the responsibility of IPageSecurity).
According to Microsoft,
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Which, if I understand, is exactly what you are trying to do here. I will admit that the structure and function for IPageSecurity does not make much sense to me, and that could be the reason behind the confusion. Bottom line, is there any reason why you would choose not to go this route? Perhaps your purpose is complicated by your example.
I have an interesting problem that I keep circling around, but I never seem to quiet find a solution.
I tend to be a defensive programmer, so I try to write code that prevents problems from happening rather than reacting to problems once they've occurred. To that end, I have the following situation. Take the following code:
public class Base {}
public Interface IBase {}
public class Derived : Base, IBase {}
public class Derived2 : Base, IBase {}
...
public class DerivedN : Base, IBase {}
public class X : Base {}
public class Y : IBase {}
I need to pass a list of objects that derive from Base and implement IBase to a collection, and I need to make sure that only objects that have both are added to the list. Additionally, there can be an arbitrary number of classes that have both, so I cannot use the derived classes as constraints.
If I make the list of type Base, then I could add a Y object. If I make it of type IBase, then objects of type X can be added (neither of which are permitted).
I could, of course create my own generic collection class that has both types and has constraints for both. But, I don't want to have to do this for all possible collection types, and it's a lot of effort to duplicate all that functionality (even if you just forward the method calls to a contained class).
I could also create a BaseWithIBase class, which derives from both Base and IBase, and use that as my collection type, but I really don't want to force another abstraction if I don't have to.
I don't want this to be a runtime check, so walking the tree and throwing exceptions is not acceptable.
Can anyone suggest a better approach to this problem?
NOTE: Base and IBase are not related, just pointing out they are both base items of different types.
EDIT:
It seems that everyone wants to insist that "you don't need to do that" and that it's "not OOP". Nothing could be further from the truth. I was attempting to remove the specific from the question to prevent these kinds of questions and comments, so I will include my real situation.
The code is an implement of a Windows Service framework, based on the .NET Frameworks ServiceProcess.ServiceBase class. I am adding my own framework on top of this, that is intended to be heavily Dependency Injection based, and highly testable.
The collection must contain objects that derive from both ServiceBase and IService. IService is my framework extension that is used in my code, and for testing. It is basically just this:
public interface IService
{
void Start();
void Stop();
}
In addition, I have a number of other interfaces:
public interface IRestartableService
{
void Restart();
}
public interface IConfigurableService
{
void Configure();
}
etc.. etc.. and a service may look like this:
public class MyService : ServiceBase, IService, IConfigurableService {}
My code requires IService, Windows requires ServiceBase, thus both are needed because I work with IService, and windows works with ServiceBase. I only require IService, the other interfaces are optional.
You can create your own wrapper collection simply:
// TODO: Work out which collection interfaces you want to implement
public class BaseList
{
// Or use List<IBase>, if that's how you'll be using it more often.
private List<Base> list = new List<Base>();
public void Add<T>(T item) where T : Base, IBase
{
list.Add(item);
}
}
By using a generic method with both constraints, you can be sure that Add can only be called with an appropriate type argument.
You could have two methods to expose the data as IEnumerable<T> - one returning IEnumerable<IBase> (using Cast<T>) and one returning IEnumerable<Base>... that would let you use LINQ on either type, but not both at the same time of course.
I suspect you may find this awkward elsewhere, however - you may find yourself littering your code with generic methods which you wouldn't typically need. While there may well be a good reason for wanting both the class part and the interface part, it would be worth taking a step back and considering whether they're really both necessary. Is there something extra you could add to the interface so that you could do away with the class constraint, for example?
There is no good answer to your question because the design itself is not really fitting OOP as implemented in C#/.NET.
If you absolutely need a collection where each element statically provides two independent interfaces, either a wrapper collection or some wrapper class like Wrapper<TFirst, TSecond, T> : IBoth<TFirst, TSecond> would solve your problem.
Example:
public interface IBoth<TFirst, TSecond> {
TFirst AsFirst();
TSecond AsSecond();
}
public class Wrapper<T, TFirst, TSecond> : IBoth<TFirst, TSecond>
where T : TFirst, TSecond
{
private readonly T _value;
public Wrapper(T value) {
_value = value;
}
public TFirst AsFirst() {
return _value;
}
public TSecond AsSecond() {
return _value;
}
}
However the real question is why do you need that. Not to say that standard OOP model is perfect, but quite often a problem can be solved much easier if original design decisions are reviewed.
Another option is to completely ignore ServiceBase in most of the code and create a ServiceBaseAdapter for communication with the code that is not interface friendly. Such adapter can just call your interface methods when its method are called.
Try something like this:
List<object> collection = new List<object>();
foreach(var obj in collection.OfType<Base>().OfType<IBase>())
{
// Do what ever you want
}
I have custom assembly that is loaded on runtime.
at this point i have code that loads dll and can create new instance of object andexecute method.
How can i verify that the class implements all functions i have defined in interface.
(i am trying to create plug in system with different action that can be switched on runtime, to provide different behaviour).
where my code would be like this is main program:
public Interface IArticleManager{
void SetMenuId(int MenuId);
void SetMenu(string name);
void SetContent(string content);
bool Save();
}
my class libraries (disconnected you can see it from solution)
public class XmlArticle{
public void SetMenuId(int MenuId){
//some implementation
}
public void SetMenu(string name){
//some implementation
}
public void SetContent(string content){
//some implementation
}
public bool Save(){
}
}
public class SqlArticle{
public void SetMenuId(int MenuId){
//some implementation
}
public void SetMenu(string name){
//some implementation
}
public void SetContent(string content){
//some implementation
}
public bool Save(){
}
}
Basically, to rephrase, you want to check if a class defines an interface's contract even if it doesn't explicitly implement that interface?
This is extremely non-trivial and a very, very bad idea. Instead, I would strongly recommend you refactor your plugin interface into a contract assembly, and reference the assembly from both your plugins and main application. Then, your plugins can actually implement the contract and you get compiler protection from messing up the implementation.
If you insist on going down this route, however:
var interfaceType = typeof(IArticleManager);
var targetType = typeof(SqlArticle);
foreach(var member in interfaceType.GetMembers())
{
var targetMember = targetType.GetMember(member.Name);
// compare the arguments, generic constraints, etc here
}
I'll leave it to you to do the comparison, because its quite honestly a substantial amount of coding. You need to check if the member is a property, event, or method, generic or nongeneric, etc.
It seems like what you need to do is move the interface into a separate assembly, which only contains interfaces which is accessible to both the 'main program' and the dynamically loaded DLLs.
So, in order to create a dynamically loaded DLL and expect it to work within your infrastructure, the author will first need to reference the interface assembly and then implement the provided interface.
Checking that a class implements all methods in an interface is of no use unless it actually implements the interface itself - the fact that it has the same method names ends up being just coincidence.
To check that an object instance implements an interface you:
if (obj is IArticleManager)
which would return true.
However if you then want to actually use the interface's methods its better (less casting):
IArticleManager manager = obj as IArticleManager;
if (manager != null)
{ do stuff }
And what is the purpose of IArticleManager when you can not use it anywhere?
That aside, if we accept that you want to make a very loose plugin system, you could mandate that every plugin assembly has exactly one public class and then instantiate that class via reflection, and call out it's methods via reflection while passing appropriate arguments.
As with every plugin or other external code you should validate the output and protect your app from errors (i.e. catch and log the plugin exceptions). This would also handle non valid plugins (ones that don't have the required signature)
Implementing Interface just provide the skeleton of the method. If we know the exact signature line of that method, in this case
what is the requirement to implement Interface?
This is the case in which Interface has been implemented
interface IMy
{
void X();
}
public class My:IMy
{
public void X()
{
Console.WriteLine("Interface is implemented");
}
}
This is the case in which Interface has not been implemented
public class My
{
public void X()
{
Console.WriteLine("No Interface is implemented ");
}
}
My obj = new My();
obj.X();
Both the approaches will produce the same result.
what is the requirement to implement Interface?
The purpose of interfaces is to allow you to use two different classes as if they were the same type. This is invaluable when it comes to separation of concerns.
e.g. I can write a method that reads data from an IDataReader. My method doesn't need to know (or care) if that's a SqlDataReader, and OdbcDataReader or an OracleDataReader.
private void ReadData(IDataReader reader)
{
....
}
Now, lets say I need that method to process data coming from a non-standard data file. I can write my own object that implements IDataReader that knows how to read that file, and my method again, neither knows nor cares how that IDataReader is implemented, only that it is passed an object that implements IDataReader.
Hope this helps.
You can write multiple classes that implement an interface, then put any of them in a variable of the interface type.
This allows you to swap implementations at runtime.
It can also be useful to have a List<ISomeInterface> holding different implementations.
There are two purposes of inheritance in .net:
Allow derived classes to share the base-class implementations of common functionality
Allow derived-class objects to be substituted for base-class objects anywhere the latter would be accepted.
Unlike some languages (C++, for example) which allow multiple inheritance, .net requires every class to have precisely one parent type (Object, if nothing else). On the other hand, sometimes it's useful to have a class be substitutable for a number of unrelated types. That's where interfaces come in.
An object which implements an interface is substitutable for an instance of that declared interface type. Even though objects may only inherit from one base type, they may implement an arbitrary number of interfaces. This thus allows some of the power of multiple inheritance, without the complications and drawbacks of full multiple-inheritance support.
You've provided a very basic example, which is probably why you're having trouble understand why. Examine something like this:
public interface IDbColumn
{
int domainID { get; set; }
}
public static IEnumerable<T> GetDataByDomain<T>(
IQueryable<T> src) where T:IDbColumn
{
string url = HttpContext.Current.Request.Url.Host;
int i = url == "localhost" ? 1 : 2;
return src.Where(x => x.domainID == i|| x.domainID == 3);
}
domainID is a physical column in every table that will reference this method, but since the table type isn't known yet there's no way to have access to that variable without an interface.
Heres simple example wich helped me to understand interfaces:
interface IVehicle
{
void Go();
}
public class Car:IVehicle
{
public void Go()
{
Console.WriteLine("Drive");
}
}
public class SuperCar:IVehicle
{
public void Go()
{
Console.WriteLine("Drive fast!!");
}
}
IVehicle car = new Car();
car.Go(); //output Drive
car = new SuperCar();
car.Go(); //output Drive fast!!
Say you have three classes, A, B, C.
A needs to accept an argument. Either B or C can be passed through.
The best way to do this is create an interface that B and C share
Well interfaces are not meant to be used with just one class, they are used accross many classes to make sure that they contain a set of methods.
a good way to visualize it is to think about driver abstraction, being able to run 1 query that can be interoperated by several different database servers.
interface DatabaseDriver
{
public function connect(ConnectionDetails $details){}
public function disconnect(){}
public function query(Query $query){}
public function prepareQuery(SQLQuery $query){}
}
and then your actual drivers would use the interface so that the database object can be assured that that the selected driver is able to perform the tasks required.
class MySqlDriver extends Database implements DatabaseDriver{}
class AccessDriver extends Database implements DatabaseDriver{}
class MsSqlDriver extends Database implements DatabaseDriver{}
hope this helps.
Note: Code in PHP