I am attempting to use an interface privately inside of a few different classes. However I wont let me call the function inside the getter you see below:
public abstract class PreFabComponent : IAccountable
{
//This represents the cumulative cost of all members, connectors, and supporting hardware
private double materialsCost;
protected double MaterialsCost
{
get
{
materialsCost = CalculateSelfCost();
return materialsCost;
}
}
// Returns the sum of all Cumulative costs
double IAccountable.CalculateSelfCost()
{
double sum = 0;
foreach (IAccountable item in accountableItemsContatined)
{
sum += item.CalculateSelfCost();
}
return sum;
}
}
Here is the interface
interface IAccountable
{
double CalculateSelfCost();
}
How can I fix this?
You need to do an explicit cast:
private double materialsCost;
protected double MaterialsCost
{
get
{
materialsCost = (this as IAccountable).CalculateSelfCost();
return materialsCost;
}
}
Basically, explicit interface method implementations are separate from other methods of a class. You simply can't call them without an explicit cast to the containing interface. In fact, there is no virtual method CalculateSelfCost in your class, in a manner of speaking.
If you want to know more about this, here is a good start - http://msdn.microsoft.com/en-us/magazine/cc163791.aspx (look specifically for the MethodTable section). You can see that the method tables for the interfaces you're implementing are separate from the method table of your class proper. In the case of implicit interface method implementations, both the main method table and the interface method table contain the reference, while in explicit implementations, the main method table doesn't have the reference at all. Now, details like this don't usually matter at all to the end-programmer, but I hope this satisfied your curiosity :)
This also has a couple of practical reasons unrelated to the internals or encapsulation practices, for example, if you had two explicit implementations of a method with the same signature but on two different interfaces, which one would you be actually calling? Rather than trying to solve the ambiguity, you simply have to always call the method properly, with the explicit interface included.
Related
Following situation:
An interface declares 2 methods which do the same action with different parameters.
interface IX
{
string DoTheThing(A a);
string DoTheThing(B b);
}
Now objects of A can be converted to B with some cost and vice versa.
Thus we might want to use an abstract class instead of the interface that would look something like that:
abstract class X
{
public virtual string DoTheThing(A a) { return DoTheThing(a.ConvertToB()); }
public virtual string DoTheThing(B b) { return DoTheThing(b.ConvertToA()); }
}
This way a subclass needs to implement only 1 of the methods if wanted.
However, it also must implement at least one of them, otherwise we get an infinite recursion.
One question is now, whether i should make one of the methods abstract and enforce the implementation?
The problem with that is that i'd have to pick one of the methods and it might be the wrong one for
some of the subclasses and result in more conversions.
So the second question is about whether i'm missing a better solution by some language features or better
design decisions (or whether i'm overthinking this)?
P.S I'm working with C#, but the answer doesn't need to be restricted to C#.
I just updated Visual Studio 2013 and I noticed that in the project template for an MVC application the ApplicationDbContext class now has a static method that just calls the constructor:
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
This seems like clutter to me but I imagine that there is some semantic reason that I should now start using ApplicationDbContext.Create() instead of new ApplicationDbContext(). Are there any benefits to doing so?
Actually. yes.
In your specific case, wrapping it thusly allows you to quickly start bolting on logic, such as making the ApplicationDbContext and singleton or handling an exception in a common way for the whole application. Since a constructor cannot return null, this can be very important to be able to catch an exception and return null.
Tuple.Create is the prime example of generic inference, which does not work with Constructors. This allows you say
Tuple.Create(Item1, Item2.. ItemN);
And the let the compiler infer types, rather than
new Tuple<T1, T2...Tn>(Item1, Item2...ItemN);
Which is more verbose, and takes a bit more work if you want to switch out one of those types.
There is also the case of Anonymous types, which cannot be specified explicitly and thus cannot be used in new statements. I have specifically had occasion where, while searching assemblies for a specific Attribute to link a command structure for, I wanted to make an enumerable (a Queue, in this case) out of an anonymous type during the search to pair class references with their constructor and string arguments, rather than looking these up every time they're needed. Since I can again use Generic inference in a method, I was able to wrap the constructor in an extension method and get the job done.
There are also cases for singleton patterns, wherein you want the "GetInstance" method to usually create a value, or get one if it exists. May not qualify since it does slightly more than wrap a constructor.
In addition, there are plenty of cases where you may want to control implementation procedures, such as forcing them onto other threads, logging them in a database to be undone later, or bolting on a permissions system, all of which can be done by making a constructor wrapper and adding a few more lines of logic, and then privatizing the constructor to avoid it being called directly.
There are also cases where I've created a factory method which delegates to known children in order to provide a different implementation of a returned interface or abstract based on provided parameters. This has the added benefit of being able to hide the implementing classes - the Type class and IEnumerable interface make use of this pattern.
This pattern can be very useful, especially if you use a private constructor, and return an interface type from the Create, rather than the concrete type.
private ApplicationDbContext()
{
}
public static IApplicationDbContext Create()
{
return new ApplicationDbContext();
}
Now consumers of your class are prevented from depending on the concrete implementation - they can only rely on the abstraction.
Wrapping the constructor with static methods (creation methods) allows you to chose a specific name that conveys information. You can also create several methods with the same parameter signature such as CreateX(float f) and CreateY(float f), which you cannot do with constructors.
A situation where this is really useful is e.g. for creating structs that represent physical quantities that may have several units, such as time, length or weight. Here, you could use creation methods to force the programmer to always explicitly specify the unit instead of just passing a unit-less number to a single constructor (which assumes a certain unit, and getting it wrong might have huge consequences).
Example:
public struct Length
{
private const double MetersPerYard = 0.9144;
private double _meters;
private Length(double meters)
{
_meters = meters;
}
public static Length FromMeters(double meters)
{
return new Length(meters);
}
public static Length FromYards(double yards)
{
return new Length(yards*MetersPerYard);
}
public double Meters
{
get { return _meters; }
}
public double Yards
{
get { return _meters / MetersPerYard; }
}
}
Or take a look at TimeSpan and methods like FromMinutes, FromSeconds etc.
Sorry if the question sounds confusing. What I mean is that if I have a class that has a method that does a bunch of calculations and then returns a value, I can either make that method public (which gives my other classes access), or I can make it private and make a public get method.
Something like this:
public publicmethod{
return privatemethod();
}
private privatemethod{
//do stuff
return value;
}
Is this a futile exercise or does it provide additional program security?
Well, there is no additional security here. However, such a usage can sometimes make sense.
For example, the private and public method may have different semantics.
// base class
public virtual BuyFood()
{
BuyPizza();
BuyCoke();
}
private void BuyPizza()
{
// ...
}
// derived class
public override void BuyFood()
{
BuyChopSuey();
}
private void BuyChopSuey()
{
// ...
}
So your implementation is just calling to a private method -- but what is important, you expose the semantics: your BuyFood operation is just BuyChopSuey(). Your code says: "in this class, buying food is just buying chop suey" in a clear way. You are able to add BuyTsingtaoBeer() into BuyFood() any time without changing the semantics of the both methods.
It is completely redundant. It does not provide anything except another name for the same thing and another indirection for readers to follow. Simply make a single implementation, and make it public. On the same note, getX() { return x; } setX(T newX) { x = newX; } does not encapsulate anything, at best it's future-proofing.
You may end up implementing a particular function required by an interface in a single line, largely delegating to (possibly private) methods which exist for other good reasons. This is different, and more justified (but again, if it's only return someMethod(); you should probably abolish the private implementation and assume the common name). A particular case if when you need two implement two methods which do the same thing (e.g. from separate interfaces).
I think either way is fine, it's more a matter of style assuming the method doesn't change the state of the class. If you have a class that has a bunch of properties and very few methods, it probably makes more sense to define another property. If you have a lot of methods in the class but few properties, then a method is more consistent with your overall class design.
If the method changes a bunch of other class variables than I'd expose it as a public method instead of a property.
I don't think either way, property or method, is necessarily more secure. It depends on what checks you do - is the caller allowed to perform the calculation? Are all variables used in the calculations within acceptable ranges? Etc. All of these checks can be performed whether you are using a property or a method.
Well, actually the question is What code do I want to be able to call this method?
Any code in general, even from other assemblies? Make the method public.
Any code from the same assembly? Make it internal.
Only code from this class? Make it private.
Having a private method directly aliased to a public method only makes the private method callable from the outside, which contradicts its private status.
If the method only does some calculation and doesn't use or change anything in the object, make it a public static method:
public static CalculationMethod(int input) {
//do stuff
return value;
}
That way any code can use the method without having the create an instance of the class:
int result = ClassName.CalculationMethod(42);
Instead of public consider internal, which would give access only to code in the same assembly.
I have a C# class that implements 2 IEnumerable interfaces. How can I access either interface from IronPython?
My class:
public class MyClass : IEnumerable<TypeA>, IEnumerable<TypeB>
{
IEnumerator<TypeA> IEnumerable<TypeA>.GetEnumerator()
{
return _lstTypeA.GetEnumerator();
}
IEnumerator<TypeB> IEnumerable<TypeB>.GetEnumerator()
{
return _lstTypeB.GetEnumerator();
}
}
I tried the following in Python, but although it runs without errors it does not return any elements from the IEnumerable interface:
x = MyClass()
xA = clr.Convert(x, IEnumerable[TypeA])
for y in xA: print y
I don't like your class design. In particular that you implement two different versions of IEnumerable<T> that return different members. Two versions that return the same members is slightly better, but I still don't like that much.
Implementing IEnumerable so it's consistent with both IEnumerable<T>s isn't possible here. In particular that breaks the OfType and Cast linq methods.
You get overload resolution problems almost everywhere. Methods like Select<T>(this IEnumerable<T> ...) don't know which IEnumerable to take.
You can't use foreach on MyClass
If both TypeA and TypeB are reference types the variance of IEnumerable<out T> comes back to bite you. Since both of them offer IEnumerable<T'> for all their common ancestors.
It doesn't interact well with dynamically types languages
A class being a two different collections at the same time rarely makes sense. It usually indicates that something went wrong in the mapping from concepts to classes.
It's confusing and hard to understand. My intuition tells me it's evil and that I should burn it with fire :P
And Probably several more issues I didn't think of yet.
The work around is simple and clean: Have two separate enumerable properties.
public class MyClass
{
public IEnumerable<TypeA> TypeAs{get{_lstTypeA.Select(x=>x)}};
public IEnumerable<TypeB> TypeBs{get{_lstTypeB.Select(x=>x)}};
}
You need to call methods and properties as you were using reflection (that is actually what it happens under the hood).
In your case you should do:
x = MyClass()
enumerator = IEnumerable[TypeA].GetEnumerator(x)
then you can loop over enumerator:
for y in enumerator:
print y
how i use specified interface
clr.AddReference('Platform.CardHost')
from Platform import CardHost
from Platform.CardHost import ICardHost
host = CardHost.CardHost.CreateInstance('session')
# ICardHost is interface
# inside C#
# public interface ICardHost {
# IExtensionManager ExtensionManager { get; }
em = ICardHost.ExtensionManager.__get__(host)
Is it possible to define an Interface with optional implementation methods? For example I have the following interface definition as IDataReader in my core library:
public interface IDataReader<T> {
void StartRead(T data);
void Stop();
}
However, in my current implementations, the Stop() method has never been used or implemented. In all my implementation classes, this method has to be implemented with throw NotImplementedExcetion() as default:
class MyDataReader : IDataReader<MyData> {
...
public void Stop()
{
// this none implementaion looks like uncompleted codes
throw NotImplementedException();
}
Of course, I can remove the throw exception code and leave it empty.
When I designed this data reader interface, I thought it should provide a way to stop the reading process. Maybe we will use Stop() sometime in the future.
Anyway, not sure if it is possible to make this Stop() method as an optional implementation method? The only way I can think is to either to define two interfaces one with stop and another without such as IDataReader and IDataReader2. Another option is to break this one into to interfaces like this:
interface IDataReader<T> {
void StartRead(T data);
}
interface IStop {
void Stop();
}
In my implementation cases, I have to cast or use as IStop to check if my implementation supports Stop() method:
reader.StartRead(myData);
....
// some where when I need to stop reader
IStop stoppable = reader as IStop;
if (stoppable != null ) stoppable.Stop();
...
Still I have to write those codes. Any suggestions? Not sure if there is any way to define optional implementation methods in an interface in .Net or C#?
Interesting. I'll have to quote you here:
However, in my current
implementations, the Stop() method has
never been used or implemented. In all
my implementation classes, this method
has to be implemented with throw
NotImplementedExcetion() as default:
If this is the case, then you have two options:
Remove the Stop() method from the interface. If it isn't used by every implementor of the interface, it clearly does not belong there.
Instead of an interface, convert your interface to an abstract base class. This way there is no need to override an empty Stop() method until you need to.
Update The only way I think methods can be made optional is to assign a method to a variable (of a delegate type similar to the method's signature) and then evaluating if the method is null before attempting to call it anywhere.
This is usually done for event handlers, wherein the handler may or may not be present, and can be considered optional.
For info, another approach fairly common in the BCL is Supports* on the same interface, i.e.
bool SupportsStop {get;}
void Stop();
(examples of this, for example, in IBindingList).
I'm not pretending that it is "pure" or anything, but it works - but it means you now have two methods to implement per feature, not one. Separate interfaces (IStoppableReader, for example) may be preferable.
For info, if the implementation is common between all implementations, then you can use extension methods; for a trivial example:
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
foreach(T item in items) list.Add(item);
}
(or the equivalent for your interface). If you provide a more specialized version against the concrete type, then it will take precedence (but only if the caller knows about the variable as the concrete type, not the interface). So with the above, anyone knowingly using a List<T> still uses List<T>'s version of AddRange; but if the have a List<T> but only know about it as IList<T>, it'll use the extension method.
If the method is inappropriate for your implementation, throw InvalidOperationException just like most iterators do when you call Reset on them. An alternative is NotSupportedException which tends to be used by System.IO. The latter is more logical (as it has nothing to do with the current state of the object, just its concrete type) but the former is more commonly used in my experience.
However, it's best to only put things into an interface when you actually need them - if you're still in a position where you can remove Stop, I would do so if I were you.
There's no unified support for optional interface members in the language or the CLR.
If no classes in your code actually implement Stop(), and you don't have definite plans to do so in the future, then you don't need it in your interface. Otherwise, if some but not all of your objects are "stoppable", then the correct approach is indeed to make it a separate interface such as IStoppable, and the clients should then query for it as needed.
If your implementation does not implement the interface method Stop, then it breaks obviousily the contract that comes with your interface. Either you implement the Stop method appropriately (not by throwing an Exception and not by leaving it empty) or you need to redesign your interface (so to change the contract).
Best Regards
C# version 4 (or vNext) is considering default implementation for interfaces - I heard that on channel9 a few months ago ;).
Interfaces with default implementation would behave somewhat like abstract base classes. Now that you can inherit multiple interfaces this could mean that C# might get multiple inheritance in form of interfaces with default implementations.
Until then you might get away with extension methods...
Or your type could make use of the delegates.
interface IOptionalStop
{
Action Stop { get; }
}
public class WithStop : IOptionalStop
{
#region IOptionalStop Members
public Action Stop
{
get;
private set;
}
#endregion
public WithStop()
{
this.Stop =
delegate
{
// we are going to stop, honest!
};
}
}
public class WithoutStop : IOptionalStop
{
#region IOptionalStop Members
public Action Stop
{
get;
private set;
}
#endregion
}
public class Program
{
public static string Text { get; set; }
public static void Main(string[] args)
{
var a = new WithStop();
a.Stop();
var o = new WithoutStop();
// Stop is null and we cannot actually call it
a.Stop();
}
}