In C# I have two classes of the form A, A where A is a customised IEnumerable over reference types and B, C are reference types that inherit from a class D. There is a property named P that exists on B, C but not D, and it would be inappropriate to add it to D as other classes inheriting from D shouldn't have P. I have instances b, c of A, A for which I need to do the following for constants x, y of the same type as P:
b.Where(v => v.P == x).ForEach(v => v.P = y);
c.Where(v => v.P == x).ForEach(v => v.P = y);
This code works, but how can I avoid repetition viz. the DRY principle?
My own efforts have encountered three major difficulties:
Since P doesn't exist on D one cannot simply create a function that works on instances of D and cast viz. b.Select(v => (D)v).
Since P doesn't exist on generic types, the compiler won't tolerate the obvious way to run this logic with a generic T.
Since A only takes T where class, a generic using A complains that T needs to be a reference type.
I'm especially interested in solutions that create a generic method on a new interface from which B, C can inherit, as I've been advised this approach should be possible.
In my opinion you want to solve a problem which doesn't exist. It will be much simpler with your class definition, but you can do something like this:
class Program
{
static void Main(string[] args)
{
int x = 1;
int y = 2;
var b = new MyCustomList<B>();
b.Foo(v => v.P == x, n => n.P = y);
}
}
public static class Extensions
{
public static void Foo<T>(this IFoo<T> #this, Func<T, bool> predicate, Action<T> action) => #this.Where(predicate).ToList().ForEach(action);
}
public interface IFoo<T> : IList<T> { }
class MyCustomList<T> : List<T>, IFoo<T> { }
class B
{
public int P { get; set; }
}
If I'm understanding you correctly, you want something similar to this:
public interface IHasPropertyP { Foo P { get; } }
public class B: D, IHasPropertyP { ... }
public class C: D, IHasPropertyP { ... }
List<D> dees = ... //I don't care if the type of the items is B, C or D
var onlyThoseWhoHavePropertyP = dees.OfType<IHasPropertyP>();
onlyThoseWhoHavePropertyP.Where(v => v.P == x).{whatever needs to be done...}
This code works, but how can I avoid repetition viz. the DRY principle?
You can remove this repetition - there are at least two ways I can think of - but consider what it gains you here. The operation you want to carry out is "Set P to Y on those objects where it is X" - this is about as simple as it gets, and having two parallel lines next to each other makes it completely clear in a way that a DRYer solution doesn't.
The two ways I can think of have been covered in other answers, but briefly:
create a common interface IHaveAPropertyP which B and C are then made to implement. Requires a code change on B and C
have a method that is passed an object of arbitrary type, along with methods for getting and seting a property P on objects of that type.
Either way, there will still be two very similar lines of code next to each other - given this, why complicate matters?
Related
So, I have searched all over stackoverflow and can't seem to find just the right answer to my question.
My question is, will equality comparison between a child object and a parent object ever return false when they point to the same memory location, and if so why? Meaning, am I soley comparing a single pointer? Or is there more going on in the background? This is related to the question "How does the compiler "see" the type of the object, and differentiate between the parent and the child (while still equating their pointers)?"
I was trying to understand this by looking at the references here and here.
Code example,
ChildType childTypeObject = new ChildType();
ParentType parentTypeObject = childTypeObject as ParentType;
if (parentTypeObject == childTypeObject)
{
// Will this always get executed?
}
EDIT:
(This is assuming the child class has not overloaded the == operator. So, if you like, use the ReferenceEquals() comparison instead.)
Will equality comparison between a child object and a parent object ever return false when they point to the same memory location, and if so why?
Sure, see below.
The == operator can be overloaded, but the compiler can only call the implementation it knows about. If only the base type overload can be applied (i.e. at least one of the operands is only the base type), then the base type implementation is called, and this implementation can easily be different from the derived type implementation.
This is why overloading the == operator (and related) should be done rarely and carefully. It takes some effort to ensure that the semantics of the operator are consistent, predictable, and match one's intuitive understanding of relationships between the objects.
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Base b = d;
Console.WriteLine($"b == d: {b == d}");
}
}
class Base
{
public static bool operator ==(Base b1, Base b2)
{
return false;
}
public static bool operator !=(Base b1, Base b2)
{
return true;
}
}
class Derived : Base
{
public static bool operator ==(Derived b1, Derived b2)
{
return true;
}
public static bool operator !=(Derived b1, Derived b2)
{
return false;
}
}
If the cast succeeds, the second variable is still the same reference as the first's and they share referential equality. It's really even the original type before the cast as far as the runtime is concerned.
void Main()
{
B b = new B();
A a = b as A;
Console.WriteLine(a.GetType().Name); // Output B
}
public class A {}
public class B : A {}
Unless you change the implementation of an operator like Peter did in his answer (or possibly through some other form of hackery) then referential equality should hold.
i have used interface in both cases. is it my first case use interface ??
here is the my interface and class
interface IAddition {
int Add();
}
interface IMultiplication {
int Multiplication();
}
it is my class
public class Calculation : IAddition, IMultiplication {
int x, y;
public Calculation(int x, int y) {
this.x = x;
this.y = y;
}
public int Add() {
return (x + y);
}
public int Multiplication() {
return (x * y);
}
}
1st case is this
class Program {
static void Main(string[] args) {
Calculation cal = new Calculation(20, 30);
Console.WriteLine("Sum is= " + cal.Add());
Console.WriteLine("Multiplication is= " + cal.Multiplication());
Console.ReadKey();
}
}
And 2nd case is this
class Program {
static void Main(string[] args) {
Calculation cal = new Calculation(20, 30);
IAddition add = (IAddition)cal;
IMultiplication mul = (IMultiplication)cal;
Console.WriteLine("Sum is= " + add.Add());
Console.WriteLine("Multiplication is= " + mul.Multiplication());
Console.ReadKey();
}
}
What is the purpose of these 2 lines ??? here what is the purpose of casting ?? Although 1st case have same output
IAddition add = (IAddition)cal;
IMultiplication mul = (IMultiplication)cal;
Only the second case programs to IAddition and IMultiplication interfaces. The first case would work even if the Calculation class did not implement IAddition and IMultiplication.
what is the purpose of casting?
Note that since you declare variables with an explicit interface type, you can safely drop the casts in the declarations of mul and add:
IAddition add = cal;
IMultiplication mul = cal;
You could also rewrite your declarations with implicit type declaration:
var add = (IAddition)cal;
var mul = (IMultiplication)cal;
What is the purpose of these 2 lines?
These lines declare two variables using the interface type implemented by Calculation. They make no practical difference in this example, but generally you could use add and mul to be specific about the level of abstraction to which you program. For example, IAddition add tells the readers of your program that you do not need to use any aspects of cal except these related to addition.
The other answers cover the given example code, but it's worthwhile to add that the rules are different for explicit interface implementation.
For example, if the example class was implemented as follows:
public class Calculation : IAddition, IMultiplication {
int x, y;
public Calculation(int x, int y) {
this.x = x;
this.y = y;
}
public int IAddition.Add() {
return (x + y);
}
public int IMultiplication.Multiplication() {
return (x * y);
}
}
then the cast is required. For example:
Calculation cal = new Calculation(10, 10);
cal.Multiplication(); // this will cause a compiler error
((IMultiplication)cal).Multiplication(); // This is the required way to do it
For more information see this article on MSDN
In this case, the purpose is just to show you how you can cast types. It doesn't make a difference in how the code works, but you can see that if you were to try add.Multiplication(), the compiler would tell you that's not allowed.
In a simple example like this, there's no reason to cast and declare variables like this. However, in larger applications, the Interface Segregation Principle helps us to avoid tight coupling of different pieces of code. For example, you could write a method like this:
int SumAll(IAddition adder, params int[] values)
{
int sum = 0;
foreach(int n in values)
{
sum = adder.Add(sum, values[i]);
}
return sum;
}
The above method would work just fine if you pass it a Calculator, but it doesn't have to use a Calculator. Since you know you don't need to multiply anything in this method, this limits your dependencies to the things that you actually need. You might in the future find it useful to implement an Add method with a ceiling, for example, that never allows numbers to go above a certain number, no matter how many things get added. Passing that IAddition object into SumAll would have a different effect, and you wouldn't have to create a different SumAll method to accommodate this need.
Console.WriteLine(SumAll(new Calculator(), 1, 2)); // 3
Console.WriteLine(SumAll(new Calculator(), 1, 2, 3)); // 6
Console.WriteLine(SumAll(new AdderWithMax(4), 1, 2)); // 3
Console.WriteLine(SumAll(new AdderWithMax(4), 1, 2, 3)); // 4
In general, people find that by separating interfaces intelligently, they're able to write code that's easier to test and less likely to require as much work when changes are made in the future--in other words, more maintainable code.
Oh, and by the way, the explicit cast isn't actually necessary, so this would also have the same effect:
IAddition add = cal;
or:
var add = (IAddition)cal;
how to use interface
There are many ways to use an inteface, from implementation to type-checking.
// Definition of interface or sometimes referred to as "Contract"
// Implementing classes must define these methods and properties
public interface IMyInterface
{
void MyMethod();
int MyProperty { get; }
}
// Implementation or sometimes referred to as "Concrete type"
public class MyClass : IMyInterface
{
public void MyMethod();
public int MyProperty { get; set; }
}
// Compile time type checking:
public void MyMethod<T>(T value)
where T : IMyInterface
{ }
// Runtime checking
public void MyMethod(object someobject)
{
var myinterface = someobject as IMyInterface;
if (myinterface != null)
{
//someobject implements IMyInterface so I can do things with it
someobject.MyMethod();
}
}
and purpose of casting?
The purpose of casting is has many uses. I'll mostly be demonstrating use the as keyword because it provides type-safety for the run-time.
You can use it to validate a type implements an interface at run-time:
public MyMethod(object obj)
{
var calc = obj as ICalc;
if (calc != null)
{
calc.Calculate();
}
}
This can be improved:
public void MyMethod(ICalc calc)
{
calc.Calculate();
}
Using generics and compile time type safety (I think it's important to show).
public void MyMethod<TObject>(TObject calc)
where TObject : ICalc
{
calc.Calculate();
}
is it my first case use interface ??
I'm not sure what this means, I think what you are trying to say is
Am I required to use the interface by casting it?
No you are not. Lets take a look at these two classes:
public class Calculation1 : IAddition, IMultiplication {
public int Add() { //... ignoring implemenetation
}
public int Multiplication() { //... ignoring implemenetation
}
}
public class Calculation2 {
public int Add() {//... ignoring implemenetation
}
public int Multiplication() {//... ignoring implemenetation
}
}
Both of the classes implement the same methods so these are valid:
var one = new Calculation1();
one.Add();
var two = new Calculation1();
two.Add();
However because the first one implements an interface and the second one does not, you can pass the first object to methods that do not need to know the concrete type.
public void MethodNeedsToAdd(IAddition addCalculator)
{
if (addCalculator != null)
{
addCalculator.Add();
}
}
MethodNeedsToAdd(one); // Valid
MethodNeedsToAdd(two); // Invalid
Even though you and I can clearly see they both can "Add" the second class two does not implement the interface.
It's all about concealing complexity. When you do this cast ...
IAddition add = (IAddition)cal;
You can then handle this add item as if all it can do is implement your IAddition interface. That might prove convenient if you were implementing a complex system.
For example, you might define an IGetNextItem interface. Then, you might choose to implement that interface in a class which fetched an item from a DBMS, and another which generated a random fake item. You would be able to cast either object, and then pass it to some software which consumed those items, without needing to tell the consuming software exactly how the fetching of items actually works.
You don't need the cast. You can say...
IAddition add = cal;
However, the point of that is you are creating an object of any type that implements the IAddition interface.
How to set nested property with autofixture (it's readonly)? Something like this:
var result =
fixture.Build<X>()
.With(x => x.First.Second.Third, "value")
.Create();
If I understand the question correctly, I'll assume that we have classes like these:
public class X
{
public X(One first, string foo)
{
First = first;
Foo = foo;
}
public One First { get; }
public string Foo { get; }
}
public class One
{
public One(Two second, int bar)
{
Second = second;
Bar = bar;
}
public Two Second { get; }
public int Bar { get; }
}
public class Two
{
public Two(string third, bool baz)
{
Third = third;
Baz = baz;
}
public string Third { get; }
public bool Baz { get; }
}
Specifically, I've added the properties Foo, Bar, and Baz to each of those classes to emphasise that while one may be interested in setting x.First.Second.Third to a specific value, one would still be interested in having all other properties populated by AutoFixture.
As a general observation, once you start working with immutable values, this is where a language like C# starts to reveal its limitations. While possible, it goes against the grain of the language.
There's plenty of other advantages to writing code with immutable data, but it gets tedious in C#. That's one of the reasons I finally gave up on C# and moved on to F# and Haskell. While this is a bit of a digression, I mention this to explicitly communicate that I think that using read-only properties is a fine design decision, but that it comes with some known problems.
In general, when working with immutable values, particularly in testing, it's a good idea to add copy-and-update methods to each immutable class, starting with X:
public X WithFirst(One newFirst)
{
return new X(newFirst, this.Foo);
}
On One:
public One WithSecond(Two newSecond)
{
return new One(newSecond, this.Bar);
}
and on Two:
public Two WithThird(string newThird)
{
return new Two(newThird, this.Baz);
}
This enables you to use Fixture's Get extension method to produce an X value with a particular First.Second.Third value, but where all other values are populated freely by AutoFixture.
The following test passes:
[Fact]
public void BuildWithThird()
{
var fixture = new Fixture();
var actual =
fixture.Get((X x, One first, Two second) =>
x.WithFirst(first.WithSecond(second.WithThird("ploeh"))));
Assert.Equal("ploeh", actual.First.Second.Third);
Assert.NotNull(actual.Foo);
Assert.NotEqual(default(int), actual.First.Bar);
Assert.NotEqual(default(bool), actual.First.Second.Baz);
}
This uses an overload to Fixture.Get that takes a delegate with three input values. All those values are populated by AutoFixture, and you can then nest the copy-and-update methods using x, first, and second.
The assertions show that not only does actual.First.Second.Third have the expected value, but all other properties are populated as well.
Lenses
You may think that it seems redundant that you have to ask AutoFixture for the first and second values, since x should already contain those. Instead, you may want to be able to just 'reach into' First.Second.Third without having to deal with all of those intermediary values.
This is possible using lenses.
A lens is a construct with the origin in category theory, and used in some programming languages (most notably Haskell). Functional programming is all about immutable values, but even with functional languages with first-class support for immutable data, deeply nested immutable records are awkward when you just need to update a single datum.
I don't intend to turn this answer into a lenses tutorial, so if you really want to understand what's going on, search for a lenses tutorial in your favourite functional programming language.
In short, though, you can define a lens in C# like this:
public class Lens<T, V>
{
public Lens(Func<T, V> getter, Func<V, T, T> setter)
{
Getter = getter;
Setter = setter;
}
internal Func<T, V> Getter { get; }
internal Func<V, T, T> Setter { get; }
}
A lens is a pair of functions. The Getter returns the value of a property, given a 'full' object. The Setter is a function that takes a value, and an old object, and returns a new object with the property changed to the value.
You can define a set of functions that operate on lenses:
public static class Lens
{
public static V Get<T, V>(this Lens<T, V> lens, T item)
{
return lens.Getter(item);
}
public static T Set<T, V>(this Lens<T, V> lens, T item, V value)
{
return lens.Setter(value, item);
}
public static Lens<T, V> Compose<T, U, V>(
this Lens<T, U> lens1,
Lens<U, V> lens2)
{
return new Lens<T, V>(
x => lens2.Get(lens1.Get(x)),
(v, x) => lens1.Set(x, lens2.Set(lens1.Get(x), v)));
}
}
Set and Get simply enables you to get the value of a property, or to set a property to a particular value. The interesting function here is Compose, which enables you to compose a lens from T to U with a lens from U to V.
This works best if you have static lenses defined for each class, for example for X:
public static Lens<X, One> FirstLens =
new Lens<X, One>(x => x.First, (f, x) => x.WithFirst(f));
One:
public static Lens<One, Two> SecondLens =
new Lens<One, Two>(o => o.Second, (s, o) => o.WithSecond(s));
Two:
public static Lens<Two, string> ThirdLens =
new Lens<Two, string>(t => t.Third, (s, t) => t.WithThird(s));
This is boilerplate code, but it's straightforward once you get the hang of it. Even in Haskell it's boilerplate, but it can be automated with Template Haskell.
This enables you to write the test using a composed lens:
[Fact]
public void BuildWithLenses()
{
var fixture = new Fixture();
var actual = fixture.Get((X x) =>
X.FirstLens.Compose(One.SecondLens).Compose(Two.ThirdLens).Set(x, "ploeh"));
Assert.Equal("ploeh", actual.First.Second.Third);
Assert.NotNull(actual.Foo);
Assert.NotEqual(default(int), actual.First.Bar);
Assert.NotEqual(default(bool), actual.First.Second.Baz);
}
You take X.FirstLens, which is a lens from X to One and first compose it with One.SecondLens, which is a lens from One to Two. The result so far is a lens from X to Two.
Since this is a Fluent Inteface, you can keep going and compose this lens with Two.ThirdLens, which is a lens from Two to string. The final, composed lens is a lens from X to string.
You can then use the Set extension method to set this lens on x to "ploeh". The assertions are the same as above, and the test still passes.
The lens composition looks verbose, but that's mainly an artefact of C# limited support for custom operators. In Haskell, a similar composition would literally look like first.second.third, where first, second, and third are lenses.
Just noticed this doesn't work:
var dict = new Dictionary<int, XElement>();
XContainer element;
//...
if (dict.TryGetValue(idx, out element)) { //...
Then I tried this:
class A { }
class B : A { }
class Program {
static void Main() {
A a;
a = Ret(); // no error, ok
Ref(ref a); // compiler error, ok...
Out(out a); // compiler error, lolwut?!
}
static B Ret() { return null; }
static void Ref(ref B b) { }
static void Out(out B b) { b = null; }
}
Why do I get a compiler error in the last call?
Edit: Ok, so as I understand from the answers 'out' is 'ref' in disguise, so it can be shared and changed by other functions or threads. But really, isn't 'out' supposed to be a way to return multiple values from a function? Because if so, it doesn't seem to be good at it. If sharing creates problems, then don't share. Just create a hidden variable at the start of the function, and work with it. I mean:
static void Out(out B b) {
B bHidden; // compiler generated;
// all references to b are replaced with bHidden;
b = bHidden;
}
Is there any reason it can't be done this way? It seems safe to me now...
as I understand from the answers 'out' is 'ref' in disguise, so it can be shared and changed by other functions or threads. But really, isn't 'out' supposed to be a way to return multiple values from a function? Because if so, it doesn't seem to be good at it. If sharing creates problems, then don't share. Just create a hidden variable at the start of the function, and work with it. I mean:
static void Out(out B b)
{
B bHidden; // compiler generated;
// all references to b are replaced with bHidden;
b = bHidden;
}
Is there any reason it can't be done this way? It seems safe to me now...
Such a system is called a "copy out" system, for obvious reasons. It could be done that way, but doing so creates interesting problems of its own. For example:
void M()
{
int b = 1;
try
{
N(out b);
}
catch (FooException)
{
Console.WriteLine(b);
}
}
void N(out int c)
{
c = 123;
P();
c = 456;
}
void P()
{
throw new FooException();
}
What is the output of the program? What should it be?
Next problem: Do you want out's behaviour to be consistent or inconsistent with ref? If you want it to be inconsistent, then congratulations, you just added a highly confusing inconsistency to the language. If you want it to be consistent then you need to make ref use "copy in copy out" semantics, which introduces a number of problems of its own, both in terms of performance and in terms of correctness.
I could go on all day enumerating the differences between reference semantics and copy semantics, but I won't. The system we've got is the system we've got, so learn to work with it.
And besides, if you want to return more than one value from a method, don't use an out parameter. That might have been the smart thing to do in 2001, but it is 2012 now and we have more tools at your disposal. If you want to return two values:
return a tuple
refactor the code into two methods that each return one value
if the two values are a value type and a bool, return a nullable value type.
Eric Lippert has written about this: http://blogs.msdn.com/b/ericlippert/archive/2009/09/21/why-do-ref-and-out-parameters-not-allow-type-variation.aspx
Modifying your example:
class A { }
class B : A { public int x; }
class Program {
static void Main() {
A a;
a = Ret();
Out(out a, () => a = new A());
}
static B Ret() { return null; }
static void Ref(ref B b) { }
static void Out(out B b, Action callback) {
b = new B();
callback();
b.x = 3; // cannot possibly work, b is an a again!
}
}
C# specification indicates types must be exact match:
17.5.1.3 Output parameters
When a formal parameter is an output parameter, the corresponding argument in a method invocation shall consist of the keyword out followed by a variable-reference (§ 12.3.3.27) of the same type as the formal parameter.
If it was allowed, you could do this:
class A { }
class B : A { public void BOnlyMethod() { } }
class C : A { }
public class Violations
{
private A a;
public void DoIt()
{
Violate(out this.a);
}
void Violate(out B b)
{
b = new B();
InnocentModification();
// what we think is B, is now C in fact, yet we still can do this:
b.BOnlyMethod();
// which is bound to fail, as BOnlyMethod is not present on type C
}
void InnocentModification()
{
this.a = new C();
}
}
If such restriction wasn't present, violations of type system like the one above would be way too easy to achieve. And I suppose you don't want this kind of "possibilities" in your language.
The question is basically: Aren't a = Ret() and Out(out a) supposed to be logically equivalent? If so, why one works and the other doesn't?
If I understand correctly, CLR doesn't actually have out and instead uses ref, which means that behind the scenes Out(out a) is implemented as Out(ref a), which fails for obvious reasons.
I'm building a system a bit like LINQ, and in doing it, am trying to support polymorphic callback handler lists, and am running into several kinds of problems. The short way to ask my question is to just show you some code. My new system supports "Groups" and groups have a vector of entry points (below, UPDATE and CHECKPT) and each element on the vector is a polymorphic list of delegates, which I'll call back using reflection.
So, sample code:
namespace ConsoleApplication1
{
internal delegate void GroupISDHandler(int i, string s, double d);
class Group
{
public class myHandlers {
internal List<Delegate> hList = new List<Delegate>();
public static myHandlers operator +(myHandlers a, Delegate b) {
a.hList.Add(b);
return a;
}
}
public class mimicVector {
public List<myHandlers> ListofhLists = new List<myHandlers>();
public myHandlers this[int i] { get { return ListofhLists[i]; } set { ListofhLists[i] = value; } }
}
public mimicVector handlers = new mimicVector();
public Group(string name) { ... }
}
class Program
{
internal const int UPDATE = 0;
internal const int CHECKPT = 1;
public static void Main()
{
Group g = new Group("group name");
g.handlers[UPDATE] += (GroupISDHandler)delegate(int x, string s, double d) {
Console.WriteLine("my int,string,double handler was called, with x = {0}, s = {1}, d = {2}",
x,s,d);
};
}
}
}
My questions centers on the registration line. Why can't C# infer the types so that I could omit the cast and the new delegate type entirely? I would think that from
g.handlers[UPDATE] += delegate(int x, string s, double d) {
Console.WriteLine(....);
};
C# could infer the needed type signature. delegate() would be a kind of anonymous type and C# would just generate something like
private delegate void _atype1(int _a0, string _a1, double _a2)
and then insert (Delegate)(_atype1) before compiling the line. Thus my user won't need to declare a delegate type (which currently forces her to type the argument list twice, in effect).
I do have System.Linq since I'm on VS 2010. So if LINQ can somehow infer the needed casts...
you should be able to do it this way:
g.handlers[UPDATE] += (GroupISDHandler)((x, s, d) =>
Console.WriteLine(
"my int,string,double handler was called, with x = {0}, s = {1}, d = {2}",
x, s, d));
another option would be:
have a class named ´Parameters´ that is a container for whatever the user can send, might be defined types if they never change, or a list of objects if you pretend to send and receive different amount of parameters. Then instead of a Delegate, you would take Action that equals a delegate that takes one argument, and you could do your call without casting like this:
p => Console.WriteLine("x = {0}, s = {1}, d = {2}", p.x, p.s, p.d);
Turns out that the answer is basically this: while you can do the inference in the kinds of situations I had in mind, the C# owners want completely general solutions and polymorphism makes the type inference problem too hard to solve in a sufficiently general way, in their view. I myself disagree since I end up typing all my type signatures twice, but that's their reasoning.