C#/Salesforce: Must Constrain Generic, Cannot Constrain Generic - c#

This question is equal parts C# and Salesforce, there are probably solutions possible from either side. Suggestions welcome!
I'm writing a generic class to read Salesforce data. The signature looks like this:
public abstract class SalesforceReader<SalesforceObjectType, RecordType>
where SalesforceObjectType: sObject
This lets me use this code later on:
List<RecordType> records = new List<RecordType>();
QueryResult queryResult = service.query(query);
foreach (sObject rawRecord in queryResult.records)
records.Add(ConvertRecord((SalesforceObjectType)rawRecord));
...
public abstract RecordType ConvertRecord(SalesforceObjectType record);
The plan is to write implementations of this class which know how to parse, for example, a Salesforce Lead object into a RecordType, which may be a basic object[], a Dictionary<string, value>, or a fully-defined struct as I choose later on.
So far, I'm all kinds of pleased with my brilliantly elegant solution. My Codey award is as good as won. Then I try to write an implementation. This definition is no good:
class LeadReader: SalesforceReader<Lead, object[]>
The compiler result is:
The type 'SalesforceExtractor.Salesforce.Lead' cannot be used as type
parameter 'SalesforceObjectType' in the generic type or method
'SalesforceUtilities.SalesforceReader<SalesforceObjectType,RecordType>'.
There is no implicit reference conversion from
'SalesforceExtractor.Salesforce.Lead' to
'SalesforceUtilities.Salesforce.sObject'.
Bummer. I have to have the where SalesforceObjectType: sObject constraint in the abstract class so I can cast sObjects, but because the conversion is not implicit, it's not good enough for the implementing class.
Do I need to kiss my neat little solution goodbye, or is there a way to salvage this? This is my first Salesforce project, so if I need to approach things differently, please let me know.
For the bad movie/MST3K buffs out there:
Where do "must" and "cannot" meet on the graph?

Aha, I just needed to walk away for half an hour and look at it again. After 20 years working with computers, you'd think I'd have learned that the problem is usually one of perspective.
Lead does inherit from sObject, but the abstract class was in a library, in a different namespace and project from the implementing class, and each of them was using the Salesforce WSDL. I was asking the compiler to cast SalesforceExtractor.Salesforce.Lead to SalesforceUtilities.Salesforce.sObject, which is not valid. I just had to be more explicit in my implementing class:
class LeadReader: SalesforceReader<SalesforceUtilities.Salesforce.Lead, object[]>
This compiles, and I think I should be good to go.

It sounds like you need to modify the Lead class to inherit from sObject. If those classes are not yours, you need to change your design.

The SF Lead object does inherit from sObject, so this is a job for generic type variance, a subset of covariance/contravariance. Good luck with your Codey acceptance speech.

Related

Adding Class<derived> to List<Class<Interface>> [duplicate]

What is the real reason for that limitation? Is it just work that had to be done? Is it conceptually hard? Is it impossible?
Sure, one couldn't use the type parameters in fields, because they are allways read-write. But that can't be the answer, can it?
The reason for this question is that I'm writing an article on variance support in C# 4, and I feel that I should explain why it is restricted to delegates and interfaces. Just to inverse the onus of proof.
Update:
Eric asked about an example.
What about this (don't know if that makes sense, yet :-))
public class Lookup<out T> where T : Animal {
public T Find(string name) {
Animal a = _cache.FindAnimalByName(name);
return a as T;
}
}
var findReptiles = new Lookup<Reptile>();
Lookup<Animal> findAnimals = findReptiles;
The reason for having that in one class could be the cache that is held in the class itself. And please don't name your different type pets the same!
BTW, this brings me to optional type parameters in C# 5.0 :-)
Update 2: I'm not claiming the CLR and C# should allow this. Just trying to understand what led to that it doesnt.
First off, as Tomas says, it is not supported in the CLR.
Second, how would that work? Suppose you have
class C<out T>
{ ... how are you planning on using T in here? ... }
T can only be used in output positions. As you note, the class cannot have any field of type T because the field could be written to. The class cannot have any methods that take a T, because those are logically writes. Suppose you had this feature -- how would you take advantage of it?
This would be useful for immutable classes if we could, say, make it legal to have a readonly field of type T; that way we'd massively cut down on the likelihood that it be improperly written to. But it's quite difficult to come up with other scenarios that permit variance in a typesafe manner.
If you have such a scenario, I'd love to see it. That would be points towards someday getting this implemented in the CLR.
UPDATE: See
Why isn't there generic variance for classes in C# 4.0?
for more on this question.
As far as I know, this feature isn't supported by CLR, so adding this would require significant work on the CLR side as well. I believe that co- and contra-variance for interfaces and delegates was actually supported on CLR before the version 4.0, so this was a relatively straightforward extension to implement.
(Supporting this feature for classes would be definitely useful, though!)
If they were permitted, useful 100% type-safe (no internal typecasts) classes or structures could be defined which were covariant with regard to their type T, if their constructor accepted one or more T's or T supplier's. Useful, 100%-type-safe classes or structures could be defined which were contravariant with respect to T if their constructors accepted one or more T consumers. I'm not sure there's much advantage of a class over an interface, beyond the ability to use "new" rather than using a static factory method (most likely from a class whose name is similar to that of the interface), but I can certainly see usage cases for having immutable structures support covariance.

Reflexive type parameter constraints: X<T> where T : X<T> ‒ any simpler alternatives?

Every so often I am making a simple interface more complicated by adding a self-referencing ("reflexive") type parameter constraint to it. For example, I might turn this:
interface ICloneable
{
ICloneable Clone();
}
class Sheep : ICloneable
{
ICloneable Clone() { … }
} //^^^^^^^^^^
Sheep dolly = new Sheep().Clone() as Sheep;
//^^^^^^^^
into:
interface ICloneable<TImpl> where TImpl : ICloneable<TImpl>
{
TImpl Clone();
}
class Sheep : ICloneable<Sheep>
{
Sheep Clone() { … }
} //^^^^^
Sheep dolly = new Sheep().Clone();
Main advantage: An implementing type (such as Sheep) can now refer to itself instead of its base type, reducing the need for type-casting (as demonstrated by the last line of code).
While this is very nice, I've also noticed that these type parameter constraints are not intuitive and have the tendency to become really difficult to comprehend in more complex scenarios.*)
Question: Does anyone know of another C# code pattern that achieves the same effect or something similar, but in an easier-to-grasp fashion?
*) This code pattern can be unintuitive and hard to understand e.g. in these ways:
The declaration X<T> where T : X<T> appears to be recursive, and one might wonder why the compiler doesn't get stuck in an infinite loop, reasoning, "If T is an X<T>, then X<T> is really an X<X<…<T>…>>." (But constraints obviously don't get resolved like that.)
For implementers, it might not be obvious what type should be specified in place of TImpl. (The constraint will eventually take care of that.)
Once you add more type parameters and subtyping relationships between various generic interfaces to the mix, things get unmanageable fairly quickly.
Main advantage: An implementing type can now refer to itself instead of its base type, reducing the need for type-casting
Though it might seem like by the type constraint referring to itself it forces the implementing type to do the same, that's actually not what it does. People use this pattern to try to express patterns of the form "an override of this method must return the type of the overriding class", but that's not actually the constraint expressed or enforced by the type system. I give an example here:
https://ericlippert.com/2011/02/02/curiouser-and-curiouser/
While this is very nice, I've also noticed that these type parameter constraints are not intuitive and have the tendency to become really difficult to comprehend in more complex scenarios
Yep. I try to avoid this pattern. It's hard to reason about.
Does anyone know of another C# code pattern that achieves the same effect or something similar, but in an easier-to-grasp fashion?
Not in C#, no. You might consider looking at the Haskell type system if this sort of thing interests you; Haskell's "higher types" can represent those sorts of type patterns.
The declaration X<T> where T : X<T> appears to be recursive, and one might wonder why the compiler doesn't get stuck in an infinite loop, reasoning, "If T is an X<T>, then X<T> is really an X<X<…<T>…>>."
The compiler does not ever get into infinite loops when reasoning about such simple relationships. However, nominal subtyping of generic types with contravariance is in general undeciable. There are ways to force the compiler into infinite regresses, and the C# compiler does not detect these and prevent them before embarking on the infinite journey. (Yet. I am hoping to add detection for this in the Roslyn compiler but we'll see.)
See my article on the subject if this interests you. You'll want to read the linked-to paper as well.
https://ericlippert.com/2008/05/07/covariance-and-contravariance-part-11-to-infinity-but-not-beyond/
Unfortunately, there isn't a way to fully prevent this, and a generic ICloneable<T> with no type constraints is enough. Your constraint only limits possible parameters to classes which themselves implement it, which doesn't mean they are the ones currently being implemented.
In other words, if a Cow implements ICloneable<Cow>, you will still easily make Sheep implement ICloneable<Cow>.
I would simply use ICloneable<T> without constraints for two reasons:
I seriously doubt you will ever make a mistake of using a wrong type parameter.
Interfaces are meant to be contracts for other parts of code, not to be used to code on autopilot. If a part of a code expects ICloneable<Cow> and you pass a Sheep which can do that, it seems perfectly valid from that point.

c# overriding enum

I know that maybe this question has been asked before, but I can't seem to find a proper solution (having in mind that I am not a C# expert but a medium level user)...
I prepared a base class including an enum (AnimationStates) for animation states that my screen objects might have (for example a Soldier might have different states whereas a bird could have another set of states..) .. The base class is serving the purpose of storing update methods and other things for my animated screen objects (like animating all of them in the same manner)... The enum in the base class is (naturally) empty inside.. I have methods written utilizing the enum members...
If I define enum in my child classes by "public new enum...", I can "inherit" it.. right ? Moreover, and interestingly, I have a Dictionary in base class and I am trying to pass it from a child (i.e. soldier, or bird) to its base (animatedobject) class ... But I can't..
I feel I am doing something wrong or missing.. Any ideas ?
Well, you cannot do it directly with enums in C#.
I would propose taking more object-oriented approach, and replace the enums with real objects. This way you define an interface IAnimationState in your base class, and add an abstract method getAnimationState() as well. In the screen object classes you just implement this method, returning some specific implementation of the interface IAnimationState. This way you can put some logic into the small animation state classes, making your project more modular.
You can't expand enums. You can create new enums in derived classes but they're distinct.
I think you should just use int constants.
An enumerated type represents a simple set of values. That's it. You are trying to use an enum as a class type when it simply doesn't fit the bill.
Just create an enum (if you actually need to) and make a "real" type for the complex operations.
enum SomeEnum { Foo, Bar }
class Whatever
{
public SomeEnum { get { return SomeEnum.Foo; } }
}
This question is a good example of developing a solution without really understanding the problem. Instead of proposing your solution and asking us to figure out the last 20% that doesn't make any sense, tell us what you are actually trying to accomplish. Someone here may have a better approach that you haven't even thought of.

Using empty parent class just to group other classes. Is there a better approach?

I have several classes that conceptually belong to one tier. They have no common properties which is why they have no need to inherit from some base class.
I also have a few methods that deal with these classes. Some of them are templates of the following style:
public SomeClass
{
public void SomeMethod<T> (T argument) where T : BaseClass
{
/* Do something */
}
}
So I'm using this WHERE keyword just to secure the code (from myself I suppose), so that I don't by mistake feed to this method something else.
Naturally I made those other classes derive from BaseClass which is empty and has no other purpose (at least for now) than to group other classes.
This is probably not that good approach but anyway I'm using it.
Is there a better way to do this?
EDIT: After consideration I decided not to go with that approach and just removed that base class. Good enough without it. I cannot make the code absolutely perfect anyway, and the less unneeded thing there are the better.
Use a marker (empty) interface instead of a base class:
public void SomeMethod<T> (T argument) where T : ISomeInterface
+1 on Jeff's answer. Tagging ("marker") interfaces are common in both C# and Java frameworks. They let you assign a common type to "class A" so that another class ("class B") can be ignorant of class A's concrete type.
As with anything this flexible, it's easy to misuse, but in your case it definitely fills the bill.
Perhaps a more concrete example would provide a little more perspective. As it stands, I'd say you should not group classes in this way.
Your SomeMethod() method obviously does not reference any of the properties of the argument (or if it does, it also must be casting the argument to different type(s)); What is the reason for securing the code "from yourself"? What would happen if you were to call the method passing in an object that was not approved?
If the argument constraint is absolutely necessary, I would recommend as Grybyx did, use an Interface. That'll save you from issues with multiple inheritance.

OOGenerics Design Considerations

Here is the situation for which I am trying to find a suitable design.
I need to store profiles of numbers. A profile is just a series of numbers. They can be of either int, float or decimal type. Each profile has a ProfileDescription field based on an ennumeration.
Each Profile has a collection of ProfileVersion Objects. Each ProfileVersion object has a collection of ProfileValue objects. These ProfileValue objects are where the actual numerical values of the required type are stored.
My initial design idea was to make Profile, ProfileVersion and ProfileValue generic. I hit a problem when I want to have a List of Profiles of different types, which I cannot have. I could use an ArrayList instead, but then i would have to cast out the data within it.
I though it might be possible to make just ProfileVersion and ProfileValue generic, and then have the Profile Object assign a type to the ProfileVersion depending on the value of the ProfileDescription field, but I cannot find a way to do this.
Another thought was I should use a ProfileBase class and then subclass it with either a GenericProfileClass or IntProfile, FloatProfile and DecimalProfile, but this wouldn't really give me any advantage over having each class being generic, as I would have to cast out the subclass each time anyway.
I would appreciate your thoughts on the best design approach for this situation.
Thanks
Grzenio's idea is correct. Each of your profile classes could be made to be implementations of an IProfile object, and then your container could be:
class ProfileList : IList<T> where T: IProfile
Thus the only constraint you'll have is the interface, not the specific type or a casted base class.
As for:
Another thought was I should use a
ProfileBase class and then subclass it
with either a GenericProfileClass or
IntProfile, FloatProfile and
DecimalProfile, but this wouldn't
really give me any advantage over
having each class being generic, as I
would have to cast out the subclass
each time anyway.
The benefits would really depend on the level of abstractions that you make for your classes. If designed properly you can ideally have operation/business logic/or manager classes that can accept any of those base types (again via generics) without having to know the specific cast.
I am not sure if I understand your problem correctly (pasting the code that doesn't work would help), but I think that you could try to create interfaces IProfile, IProfileVersion, etc. and make the generic class inherit the interface Profile<T>:IProfile.
What you are trying to do in not easy anyway, because there is no base numeric type in C# sadly.

Categories

Resources