C#: Add conditional generic method (different generic restriction) within generic class - c#

I'm trying to add another restriction on a method within a generic class. Is this possible?
Pseudocode:
public class MyBaseClass<T> where T: class
{
public IQueryable<T> ShowThisMethod where T: class, IMyInterface
{
// stuff.
}
}
ShowThisMethod should only be available when T is IMyInterface. Also IMyInterface should then give information back (about T) so that I can access properties defined in IMyInterface inside of the method.
Help :)
By the way, this compiles (and seems "almost right"):
public class MyBaseClass<T> where T: class
{
public IQueryable<T> ShowThisMethod<T>() where T: class, IMyInterface
{
String X = T.MyInterfaceStringProperty;
}
}
More Information about my goal:
I'm using a generic base class to access a common property (DateTime "Time" property on LINQ object Dinner which is also on Lunch).
Both objects are implementing ITimeable which exposes the DateTime property.
In my base class I'd like to have a method Select() which works on IQueryable&ltT> and can automatically filter based on the Time property. Because I'm working off the generic T, the time property is not visible to the base class, unless I tell it that T is implementing ITimeable.
I do want the same base class to work for other non-ITimeable objects too, that's why I need the interface restriction on the Select method, and I also need it in order to access the Time property using generics.
Hope that clears the goal :)
P.S. My main concern is not visibility of the method in IntelliSense etc.. I'd just like to keep my base class working, while being able to access an interface-specified property through generics in it.

It depends on what you want.
Since the class is compiled once, and the magic with generics also relies on the runtime, there's no way to make a class that has some methods in some cases, and other methods in other cases. Either the methods are there, or they aren't.
So basically, there's no way to declare MyBaseClass so that the following happens:
MyBaseClass<Int32> bc;
bc. <-- intellisense does not show ShowThisMethod here
MyBaseClass<SomeTypeImplementingIMyInterface> bc2;
bc2. <-- intellisense DOES show ShowThisMethod here
... that is... by itself.
You can "trick" the compiler and intellisense into giving you what you're asking for, but know that this gives you other limitations and challenges that might need to be solved.
Basically, by adding an extension method to a static class declared alongside MyBaseClass, you can make intellisense, and the compiler, behave as if the method is only present for MyBaseClass when T has some specific rules, as you're asking for.
However, since the method in question will be a static method, defined outside of MyBaseClass, there's limits to how much of the internals of MyBaseClass you can access, and you can't access the method inside MyBaseClass, so it depends on what you want to accomplish and whether you can live with the limitations or not.
Anyway, here's the extension method. Note that you remove it completely from MyBaseClass at the same time:
public static class MyBaseClassExtensions
{
public static IQueryable<T> ShowThisMethod<T>(this MyBaseClass<T> mbc)
where T: class, IMyInterface
{
...
}
}

Also note that ShowThisMethod is redefining T in the context of ShowThisMethod. It is not the same T as defined by the class.
Specifying a different Type parameter where the new one inherits from the one defined by the class would be the best approach, though that ends up requring the caller to have to specify the generic Type twice.

No, it's not possible. Constraints are defined when they are declared. In this case, the method is not generic, the class is (it's a non-generic method of a generic class). So the constraints can be only declared on the class itself.

Will this do what you want? The method will be visible to anyone, but not necessarily useable...
public class MyBaseClass<T> where T: class
{
public IQueryable<R> ShowThisMethod() where R: T, IMyInterface
{
Debug.Assert(typeof(R) == typeof(T));
// stuff.
}
}

You could define another class that inherits MyBaseClass and redefine the constraint :
public MyOtherClass<T> : MyBaseClass<T> where T : class, IMyInterface
{
public IQueryable<T> ShowThisMethod()
{
// stuff.
}
}

Related

.Net generics -- implementation inheritance from interface

I have two sequences of objects 'A' and 'B'. Comparing the sequences should produce a third sequence 'C' of elements that indicate whether:
the objects were "deleted" from 'A' or
"inserted" from 'B'.
All remaining elements are considered as "matched".
What I would like to do:
Declare Inserted<T>, Deleted<T>, and Matched<T> generic classes that inherit all their properties from the T base class. The generic class must be able to instantiate itself from the object it inherits.
The code:
public interface IInstantiable<T>
{
void CopyFrom(T o);
}
[Serializable]
public class Inserted<T> : T
where T : IInstantiable<T>
{
public Inserted() { }
public Inserted(T t)
{
this.CopyFrom(t);
}
}
The error:
'MyNamespace.Inserted<T>' does not contain a definition for 'CopyFrom' and no
extension method 'CopyFrom' accepting a first argument of type 'MyNamespace.Inserted<T>'
could be found (are you missing a using directive or an assembly reference?)
Further discussion:
I define my own IInstantiable interface to enforce the existence of a CopyFrom method. I cannot use the standard ICloneable interface, because it only defines a method that copies the object to a new instance, whereas I need the object to copy its members in the constructor.
The error goes away if the generic defines its own implementation of the CopyFrom method; however, this does not achieve the desired goal of specializing the CopyFrom method to handle the specific needs of the base class. Only the base class could know what properties should be copied. (Or am I missing something?)
Note: The final object should have the same public members as its base class, as the object should be capable of serialization.
Is this possible in .NET?
The answer:
What I am attempting to do is impossible, simply because the generic class cannot be an extension of the template base class. Visual Studio complains "Cannot derive from 'T' because it is a type parameter." (I hadn't noticed this error yet because I had not implemented the CopyFrom method in the generic class yet.)
If I were to change the interface into a class and supply a stub implementation in that class, I could inherit from it as suggested below; however, this introduces a new base class into my inheritance hierarchy.
public class IInstantiable<T>
{
public virtual void CopyFrom(T o) { }
}
[Serializable]
public class Inserted<T> : IInstantiable<T>
where T : IInstantiable<T>
{
public Inserted() { }
public Inserted(T t)
{
base.CopyFrom(t);
}
}
Unfortunately, I cannot use this new base class in its templatized form because I must introduce it at the root of my inheritance hierarchy. It works only if I remove the template and make it as generic as possible.
public class IInstantiable
{
public virtual void CopyFrom(Object o) { }
}
However, this still does not make my Inserted<T> generic look like the object it is initialized from, and since I cannot inherit from the same type as the type parameter, it does not suit my initial purpose.
Moving away from "fancy generics" based on the type system to more (ahem) generic annotated structures might prove to be the best solution; however, the default behavior of my selected serialization approach (XmlSerialization) does not have the automatic support that would make this configuration a viable solution. Generics will not work; use hard-coded class definitions instead.
This is indirectly what you're trying to declare in your code above.
[Serializable]
public class Inserted<T> : IInstantiable<T>
where T : IInstantiable<T>
{
public Inserted() { }
public Inserted(T t)
{
this.CopyFrom(t);
}
}
Does this make sense?
.NET doesn't allow you to inherit from a generic parameter. How could it? Generics are evaluated at runtime but it needs to know what type your class is at compile time.
If I understand correctly, you want to annotate a sequence of objects with the notion of what their state is (inserted, deleted, or matched).
You don't really need fancy generics for this; what's wrong with:
enum ChangeState { Inserted, Deleted, Matched }
struct<T> Annotated {
public T Obj;
public ChangeState;
}
You can mark this for serialization however you want (the Annotated object can serialize just fine without the same properties/fields).
Though you can encode more information in the type system, it's unclear to me what the benefit would be here. Are you sure you want to do that?

Abstract Method in Non Abstract Class

I want to know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#).
I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same?
They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as #ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract.
Or another way to put it: if you had an abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.
Now, I'll try to be more concrete by using an example: imagine the following code:
Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };
foreach (Animal animal in zoo)
animal.MakeSound();
Here, Animal is the non-abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options:
You can't call MakeSound() on a variable typed as Animal, you can call it only using a variable typed as one of the derived classes, so this is a compile error.
This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract, virtual or override) method into each derived class and don't do anything with the base class.
You can't call MakeSound() on an object whose runtime type is actually Animal, so this is a runtime error (an exception).
This is also not a good solution. C# is a statically typed language and so it tries to catch errors like “you can't call this method” at compile time (with obvious exceptions like reflection and dynamic), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception.
To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented.
So, you want to allow
class C { abstract void M(); }
to compile. Suppose it did. What do you then want to happen when someone does
new C().M();
? You want an execution-time error? Well, in general C# prefers compile-time errors to execution-time errors. If you don't like that philosophy, there are other languages available...
I think you've answered your own question, an abstract method isn't defined initially. Therefore the class cannot be instanciated. You're saying it should ignore it, but by definition when adding an abstract method you're saying "every class created from this must implement this {abstract method}" hence the class where you define the abstract class must also be abstract because the abstract method is still undefined at that point.
The abstract class may contain abstract member. There is the only method declaration if any method has an abstract keyword we can't implement in the same class. So the abstract class is incompleted. That is why the object is not created for an abstract class.
Non-abstract class can't contain abstract member.
Example:
namespace InterviewPreparation
{
public abstract class baseclass
{
public abstract void method1(); //abstract method
public abstract void method2(); //abstract method
public void method3() { } //Non- abstract method----->It is necessary to implement here.
}
class childclass : baseclass
{
public override void method1() { }
public override void method2() { }
}
public class Program //Non Abstract Class
{
public static void Main()
{
baseclass b = new childclass(); //create instance
b.method1();
b.method2();
b.method3();
}
}
}
You can achieve what you want using "virtual" methods but using virtual methods can lead to more runtime business logic errors as a developer is not "forced" to implement the logic in the child class.
I think there's a valid point here. An abstract method is the perfect solution as it would "enforce" the requirement of defining the method body in children.
I have come across many many situations where the parent class had to (or it would be more efficient to) implement some logic but "Only" children could implement rest of the logic"
So if the opportunity was there I would happily mix abstract methods with complete methods.
#AakashM, I appreciate C# prefers compile time errors. So do I. And so does anybody. This is about thinking out-of-the-box.
And supporting this will not affect that.
Let's think out of the box here, rather than saying "hurrah" to big boy decisions.
C# compiler can detect and deny someone of using an abstract class directly because it uses the "abstract" keyword.
C# also knows to force any child class to implement any abstract methods. How? because of the use of the "abstract" keyword.
This is pretty simple to understand to anyone who has studied the internals of a programming language.
So, why can't C# detect an "abstract" keyword next to a method in a normal class and handle it at the COMPILE TIME.
The reason is it takes "reworking" and the effort is not worth supporting the small demand.
Specially in an industry that lacks people who think out of the boxes that big boys have given them.
It's still not clear why you would want that, but an alternative approach could be to force derived classes to provide a delegate instance. Something like this
class MyConcreteClass
{
readonly Func<int, DateTime, string> methodImpl;
// constructor requires a delegate instance
public MyConcreteClass(Func<int, DateTime, string> methodImpl)
{
if (methodImpl == null)
throw new ArgumentNullException();
this.methodImpl = methodImpl;
}
...
}
(The signature string MethodImpl(int, DateTime) is just an example, of course.)
Otherwise, I can recommend the other answers to explain why your wish probably isn't something which would make the world better.
So the answers above are correct: having abstract methods makes the class inherently abstract. If you cannot instance part of a class, then you cannot instance the class itself. However, the answers above didn't really discuss your options here.
First, this is mainly an issue for public static methods. If the methods aren't intended to be public, then you could have protected non-abstract methods, which are allowed in an abstract class declaration. So, you could just move these static methods to a separate static class without much issue.
As an alternative, you could keep those methods in the class, but then instead of having abstract methods, declare an interface. Essentially, you have a multiple-inheritance problem as you want the derived class to inherit from two conceptually different objects: a non-abstract parent with public static members, and an abstract parent with abstract methods. Unlike some other frameworks, C# does permit multiple inheritance. Instead, C# offers a formal interface declaration that is intended to fill this purpose. Moreover, the whole point of abstract methods, really, is just to impose a certain conceptual interface.
I have a scenario very similar to what the OP is trying to achieve. In my case the method that I want to make abstract would be a protected method and would only be known to the base class. So the "new C().M();" does not apply because the method in question is not public. I want to be able to instantiate and call public methods on the base class (therefore it needs to be non-abstract), but I need these public methods to call a protected implementation of the protected method in the child class and have no default implementation in the parent. In a manner of speaking, I need to force descendants to override the method. I don't know what the child class is at compile time due to dependency injection.
My solution was to follow the rules and use a concrete base class and a virtual protected method. For the default implementation, though, I throw a NotImplementedException with the error "The implementation for method name must be provided in the implementation of the child class."
protected virtual void MyProtectedMethod()
{
throw new NotImplementedException("The implementation for MyProtectedMethod must be provided in the implementation of the child class.");
}
In this way a default implementation can never be used and implementers of descendant implementations will quickly see that they missed an important step.

Circular generic types in inheritance - why does it work?

Consider the following:
public class EntityBase<TEntity>
{
public virtual void DoSomethingWhereINeedToKnowAboutTheEntityType()
{
}
}
public class PersonEntity : EntityBase<PersonEntity>
{
public override void DoSomethingWhereINeedToKnowAboutTheEntityType()
{
}
}
I added this into code and ran it and it worked ok, but I'm surprised that I can inherit a class who's definition is based on the inheriting class.
When I tried it I was expecting either it not to compile, or to fail once actually called.
You can do something similar with an interface:
public interface IEntityBase<TEntity>
{}
public class PersonEntity : IEntityBase<PersonEntity>
{}
I've actually switched my code from the former to the later, using the interface, but I'm still curious why this works.
It works because there's no reason why it wouldn't work. EntityBase<PersonEntity> doesn't inherit from PersonEntity, it merely references the type. There's no technical problem with a base class knowing about its own derived class. This also works (even though this specific example is a bad idea):
public class A
{
public B AsB()
{
return this as B;
}
}
public class B : A
{
}
I'm surprised that I can inherit a class who's definition is based on the inheriting class.
Careful - what you're inheriting is a class whose definition involves an arbitrary Type, is all. All of these are legal:
class O : EntityBase<object>
class S : EntityBase<String>
class Q : EntityBase<Q>
All you've said in the definition of EntityBase is that TEntity should be a type - well, PersonEntity is a type, isn't it? So why shouldn't it be eligible to be a TEntity? No reason why not - so it works.
You might be concerned about the order of definitions, but remember that within the unit of compilation, everything gets defined 'at once' - there's no sense in which PersonEntity needs to be compiled 'before' anything else (including itself!) can refer to it. Indeed, you're even allowed
class A : EntityBase<B>
class B : EntityBase<A>
for which no conceivable 'order of compilation' could work, if such a thing were needed.
A very simple example is the generic interface IComparable<T>. Usually, you implement it like this:
class MyClass : IComparable<MyClass> {/*...*/}
This implementation of the generic template is just saying that MyClass objects can compare to other MyClass objects. As you can see, there is no problem with the mental model. I can very well understand the concept of a class whose objects can compare between them without knowing anything else about the class.
The main point here is that template parameters are just used by the generic class or interface, but they need not be related by inheritance at all. IComparable<MyClass> does not inherit from MyClass. So there is no circularity.

abstract method use vs regular methods

I would like to know the difference between two conventions:
Creating an abstract base class with an abstract method
which will be implemented later on the derived classes.
Creating an abstract base class without abstract methods
but adding the relevant method later on the level of the derived classes.
What is the difference?
Much like interfaces, abstract classes are designed to express a set of known operations for your types. Unlike interfaces however, abstract classes allow you to implement common/shared functionality that may be used by any derived type. E.g.:
public abstract class LoggerBase
{
public abstract void Write(object item);
protected virtual object FormatObject(object item)
{
return item;
}
}
In this really basic example above, I've essentially done two things:
Defined a contract that my derived types will conform to.
Provides some default functionality that could be overriden if required.
Given that I know that any derived type of LoggerBase will have a Write method, I can call that. The equivalent of the above as an interface could be:
public interface ILogger
{
void Write(object item);
}
As an abstract class, I can provide an additional service FormatObject which can optionally be overriden, say if I was writing a ConsoleLogger, e.g.:
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
}
By marking the FormatObject method as virtual, it means I can provide a shared implementation. I can also override it:
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
protected override object FormatObject(object item)
{
return item.ToString().ToUpper();
}
}
So, the key parts are:
abstract classes must be inherited.
abstract methods must be implemented in derived types.
virtual methods can be overriden in derived types.
In the second scenario, because you wouldn't be adding the functionality to the abstract base class, you couldn't call that method when dealing with an instance of the base class directly. E.g., if I implemented ConsoleLogger.WriteSomethingElse, I couldn't call it from LoggerBase.WriteSomethingElse.
The idea of putting abstract methods in a base class and then implementing them in subclasses is that you can then use the parent type instead of any specific subclass. For example say you want to sort an array. You can define the base class to be something like
abstract class Sorter {
public abstract Array sort(Array arr);
}
Then you can implement various algorithms such as quicksort, mergesort, heapsort in subclasses.
class QuickSorter {
public Array sort(Array arr) { ... }
}
class MergeSorter {
public Array sort(Array arr) { ... }
}
You create a sorting object by choosing an algorithm,
Sorter sorter = QuickSorter();
Now you can pass sorter around, without exposing the fact that under the hood it's a quicksort. To sort an array you say
Array sortedArray = sorter.sort(someArray);
In this way the details of the implementation (which algorithm you use) are decoupled from the interface to the object (the fact that it sorts an array).
One concrete advantage is that if at some point you want a different sorting algorithm then you can change QuickSort() to say MergeSort in this single line, without having to change it anywhere else. If you don't include a sort() method in the parent, you have to downcast to QuickSorter whenever calling sort(), and then changing the algorithm will be more difficult.
In the case 1) you can access those methods from the abstract base type without knowing the exact type (abstract methods are virtual methods).
The point of the abstract classes is usually to define some contract on the base class which is then implemented by the dervied classes (and in this context it is important to recognize that interfaces are sort of "pure abstract classes").
Uhm, well, the difference is that the base class would know about the former, and not about the latter.
In other words, with an abstract method in the base class, you can write code in other methods in the base class that call that abstract method.
Obviously, if the base class doesn't have those methods... you can't call them...
An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality...
And of course, if you override a virtual method, you can always refer to the parent method by calling base.myVirtualMethod()
Okay, when you see a method like this:
A.Foo();
What you really have (behind the scenes) is a signature like this.
Foo(A x);
And when you call A.Foo() you're really calling Foo(this) where this is a reference to an object of type A.
Now, sometimes you'd like to have Foo(A|B|C|D...) where Foo is a method that can take either a type A, or B, or C, or D. But you don't want to worry about what type you're passing, you just want it to do something different based on the type that was passed in. Abstract methods let you do that, that's their only purpose.

Is it possible to make an abstract method's parameter list have overridable length and types?

Is it possible to create a base class like the following:
public abstract class baseClass
{
public abstract void SetParameters(/*want this to be adjustable*/);
}
so that classes that override it can define the parameters required?
In other words, I want to force the method to be overridden, but leave it up to the overriding class what is required here - so one might be
public class derivedClass1 : baseClass
{
public override void SetParameters(Point a, int b);
}
whereas another could be
public class derivedClass2 : baseClass
{
public override void SetParameters(List<Line> a, Point b, Point c, bool e);
}
?
Thanks for any help you can give
Absolutely not - that would break half the point of having the abstract method in the first place - no-one would be able to call it, because they wouldn't know which method signature had actually been written. The whole point of an abstract class is that a client can have a reference of type BaseClass without caring about what the type of the actual implementation is.
If the base class is able to predict in advance which types might be involved, one possibility to make life easier for the caller is to have the most general signature (typically the one with the most parameters) abstract, and make various overloads which call that general one providing defaults for the parameters that the client hasn't specified.
It can be done IF the parameters were all set to the same type and in the same number i guess (not sure if you can use params T[], but if its possible, then you can adjust it too). You can achieve by using Generics, like #simonalexander2005 said
public abstract class baseClass<T> where T : class
{
public abstract T SetParameters(params T[] parameters);
}
its up to you to decide how many parameters the derived class will use. But, im not sure if its a good practice...
No, this isn't possible. An overriding method needs to match the parameters exactly—it's the same as implementing an interface. You may be interested in the double-dispatch pattern.

Categories