Extend a generic partial class - c#

my question could seem strange.
I use a class to encapsulate a method to not have to build a class of the interface (it's a bit long to explain and i don't want to go too far).
I would to know if it was possible to "extend" a generic class by add partial to "extend" its generic part. The purpose is to keep the same name class, but by add one (or more in the future) generic type to have the possibility to encapsulate any method, then pass the object containing the function and that include this interface.
I need to have:
new Foo<string>()
new Foo<string, int>()
...
I 'successful' made this i think, but perhaps it will generate some bug i can't imagine right now, or perhaps it's not.. how to say a good way to program.
Example:
Original
// A class to encapsulate a method "without parameter"
partial Foo<T>: Interface
{
public Func<Interface, T> FooLambda{ get; set; }
public virtual object Run()
{
return ToRun(this);
}
}
The method i need to pass (from another class)
void FooToEncapsulate(Interface patt)
{
//--- My code using an object with the interface pattern
}
Add another generic Type to Foo
The part to "extend" Foo
partial Foo<T,Y>: Foo<Y>
{
public new Func<Interface, T, Y> FooLambda{ get; set; }
public T Param {get;set;}
public override object Run()
{
return this.ToRun(this, Param);
}
}
The other method i need to pass (from another class)
void FooToEncaspulate(Interface patt, int param)
{
//--- My code using an object with the interface pattern
//--- and "param"
}
I have no problem for the while with this code, and i know it's something that could be strange, must i forget to use this technic, or could i think it was thought to work also like this ? Must i think if it compiles that means it's ok ? Is there another way to proceed like this without create a new class, and extend in same time on the generic part ?
(Sorry for my english)
Thx.
Edit:
I thought by using partial that could be a good idea, because i would to keep the same name for my class. After have read an answer and comment from Enigmativity, i tried without partial, and i have no errors relating to the name of the class when i compile.
If i well understand, the fact to add generic parameter to a class makes that create as many class than as "variants" depending on the generic type. "Partial" is useful to split code on several files on a basic class.
Is partial could be useful on code split with the same number of generic type ?

You don't need the word partial to extend a class with a single generic type to have two generic types. They are in fact two distinct classed.
This works fine:
class Foo<T>
{
}
class Foo<T, Y> : Foo<Y>
{
}
Now, as said in the comments, the rest of your code is quite flaky. If you can clean up the code I could provide you with a more answer that will be of more use to you.

Related

NUnit 3 dynamic ValueSourceAttribute

I have to convert NUnit 2.x tests to NUnit 3.x tests and currently have the situation that there is one base class with tests and abstract IEnumerable property used in ValueSource for these tests and many classes that inherits this base class and overrides this property.
The question is how to convert these tests to NUnit 3.x where ValueSource has to be static. Each base child also has different TestCategory.Subcategory.
[Category(TestCategory.Transformations)]
public abstract class Transformations
{
[Test]
public void TransformTest([ValueSource("TestDataSource")] TransformTestSource source)
{
// some test logic
}
protected abstract IEnumerable<TransformTestSource> TestDataSource { get; }
}
[TestFixture]
[Category(TestCategory.Transformations)]
[Category(TestCategory.Subcategory.Example1)]
public class ChildExample1
{
protected override IEnumerable<TransformTestSource> TestDataSource
{
get { /* get data for example from database, or file */ }
}
}
The only way in my mind is to remove abstract property definition from abstract class and define this property in each child class but it sounds awful. Is there a better way?
EDIT: Sometimes, there are also some other tests in child class, so those classes are there not always only for data fill.
The base class must be abstract else NUnit will instantiate it and run the tests it contains. Of course it will also re-run the same tests when it instantiates the base class. This is at best confusing and at worst will give errors when the tests are run on the base class alone.
You use the term dynamic in the question without explanation. If what you mean by that is an instance method or property, then this answer is for you. Of course, the contrary of a static method is an instance method in C# and "dynamic" is something else. In any case, if you do mean something else, please edit your question to explain.
So... while NUnit 3 requires your source to be static, that doesn't limit you to only using things that are known at compile time. If your source is a static method rather than a field, then it's possible for you to discover the necessary information to generate the data (in some sense) "dynamically."
It is also possible in NUnit 3 to use TestCaseSource to contain your data. In that case, Form 3 of the attribute constructor (see the docs) does allow use of an instance member. This form, however, puts your data in a separate class from your tests and may not suit your usage.
I had the same issue and found a solution using the TestCaseSource with a method name and a manual implementation that works in a similar way as Form 3 of TestCaseSource.
I made the base class abstract and gave it a generic parameter. This generic parameter is used to indicate the class that generates the test cases (similar to Form 3 of TestCaseSource).
I add a static method that generates the test cases based on the generic type parameter. This static method is then used as the test case source. In each sub class I can then add a custom class to generate its test cases.
The base class is as follows then:
[TestFixture]
public abstract class BaseTest<TCases>
where TCases : IEnumerable, new()
{
public static IEnumerable TestCases()
{
TCases t = new();
foreach (object o in t)
{
yield return o;
}
}
[Test]
[TestCaseSource(nameof(TestCases))]
public void TestACase(int? case)
{
Assert.That(case, Is.Not.Null);
}
}
Then in the derived class, I define an inner class that generates the test cases, as follows.
public class Derived
: BaseTest<Derived.MyCases>
{
public class MyCases : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 5;
}
}
}
This solution seems to work just fine and I'm quite pleased with it.
In the example I use TestCaseSource, but you should be able to use the same technique with ValueSource.

C# - specific type method declaration inside a generic class

I'm trying to achieve a general purpose "mutable" method using a generic class, i don't know if C# can achieve this. I'll explan the situation: I have a class that represents an entity in a database whose properties are marked with attributes [PrimaryKey] and [Field]. Example:
public class Car :TableEntity
{
[Field]
[PrimaryKey]
public string RegNumber{get;set;}
[Field]
public string Color{get;set;}
}
What I try to achieve is that instantiating a generic class using a TableEntity class, the .GetOne() method automatically change its parameters to be those of the primary keys, but I have not been able to find an elegant way to do it.
For example, i have:
public class BusinessObject<T> where T:TableEntity
{
public T GetOne(); //this is the method to modify depending on which type is T
}
and if i do
BusinessObject<Car> BO = new BusinessObject<Car>();
i should see in the Intellisense:
BO.GetOne(string RegNumber);
Is there a way or a workaround to achieve this? I know that using System.Reflection i can extract the parameter names and types which are marked as [PrimaryKey], but i don't know if i can modify a method declaration "on the air".
Thank you very much!
You'd have to add a generic parameter and propagate it:
public abstract class TableEntity<TKey>
{
}
public class BusinessObject<TEntity, TKey>
where T : TableEntity<TKey>
{
public TEntity GetOne(TKey key)
{
// ...
}
}
C# is statically typed language from CLR point of view, hence for sure it does not allow for on-the-fly changes but if you touch DLR available from .Net4.0 onwards you have to sacrify intellisense luxury.
As an alternative you may modify the core class/interface to accept generic parameter as well along with other parameters.

Return array of 'this' in C#

I have a library which contains a class. This class is meant to be extended. It will connect to a database and generate entries of the class which extends it. Now I want to return an array of the type of the extending class. How can I do this ? For example :
public this[] search(string search) {
}
How can I perform this ?
EDIT :
I'm using generics, it's a generic class. Which means I don't have any clue on what the class which will extend mine will be. So no I can't just add the class name before the []...
EDIT 2:
As it has been pointed out, returning an array of this doesn't make any sense (my mistake then). So what I want to do is return an array of the extending class type.
For example :
public abstract class MappingObject {
public ExtendedClassType[] search (string search) {
}
}
Found the solution ._. I'm sorry it was quite simple...
public abstract class MappingObject<T> where T : new() {
public static List<T> search(string search) {
}
}
I'm not entirely sure what you are looking for, but based on a few clues in your question you might want to review something like the following (referred to as the Curiously Recurring Template Pattern):
public abstract class MyBaseClass<T> : where T : MyBaseClass<T>
{
public abstract T[] Search(string search);
}
public class DerivedClass : MyBaseClass<DerivedClass>
{
public override DerivedClass[] Search(string search)
{
return new DerivedClass[0];
}
}
This is possible, but I'm not sure if it is what you are looking for and I'd review to see if this was a good design choice or not, it feels a little leaky.
This particular idea is used in frameworks like CSLA.NET in order to expose to derived class strong references to themselves when inheriting from certain base classes. This is usually a "syntax sugar" thing, and avoids having to cast up a lot just to use things on your own type when retrieving them from base classes. The base class itself still should not understand what types are deriving from it.
Eric Lippert talks about this pattern on his old MS blog. It has its pitfalls and he exposes a manner in which it can be abused. I personally stand by the approach that being aware of these pitfalls and possibilities for abuse is good enough, so long as things are tested I'm happy to use something that might go against guidelines or principles if the case is clear (there isn't enough additional information to understand if it is clear in this particular case). Eric's post ends:
All that said, in practice there are times when using this pattern really does pragmatically solve problems in ways that are hard to model otherwise in C#; it allows you to do a bit of an end-run around the fact that we don't have covariant return types on virtual methods, and other shortcomings of the type system. That it does so in a manner that does not, strictly speaking, enforce every constraint you might like is unfortunate, but in realistic code, usually not a problem that prevents shipping the product.
My advice is to think very hard before you implement this sort of
curious pattern in C#; do the benefits to the customer really outweigh
the costs associated with the mental burden you're placing on the code
maintainers?
The best use of this pattern I have seen left all the recurring parts internal or protected and the public API was left alone.
'this' means this instance of a class, so your code at the minute basically says 'I want to return an array of this instance of MyClass' which doesn't really make sense.
I think you want to say 'I want to return an array of this type of class object'
So you specify the return type of the method as the class name.
public YourClassName[] Search(string search)
{
}
Do you mean,
public class YourClass
{
public T[] Search<T>(string search, Convertor<SearchResult, T> convertor)
{
...
List<SearchResult> results = ...
return results.ConvertAll(convertor).ToArray();
}
}
This way, you delegate the conversion to the caller who will know what type is passed as the generic type parameter.

One method shared by several classes

I have just one method that I need several different classes to access and it just seems lame to make a utility class for just one method. The classes that need to use this method are already inheriting an abstract class so I can't use inheritance. What would you guys do in this situation?
[I]t just seems lame to make a utility
class for just one method
Just do it, it will grow. It always does. Common.Utilities or something of that nature is always necessary in any non-trivial solution.
Keep in mind that a class is just a small, focused machine. If the class only has one method then it's just a very small, focused machine. There's nothing wrong with it, and centralizing the code is valuable.
There is a cheat that you can use :-)
Create an Interface that your classes can "implement" but, create an extension method on that interface, your classes then magically get that method without having to call the utility class...
public Interface IDoThisThing {}
public static void DoThisThingImpl(this IDoThisThing dtt)
{
//The Impl of Do this thing....
}
Now on your classes you can just add the IDoThisThing
public class MyClass, MyBaseClass, IDoThisThing
{
//...
}
and they Get that thing :-)
Note, this is only syntatic sugar around effectively a utility class, but it does make the client code very clean (as just appears as a method on your class).
What do you mean you can't use inheritance?
If you write the method in the abstract class, you can also write the implementation (not everything in an abstract class needs to be abstract).
But generally, it's advisable to have some sort of 'GeneralUtils' class; cause you end up with a few of these functions.
I'd need more info to give a definite answer.
However a well-named class with a single well-named method could work wonders for readability (as compared to an inheritance based solution for instance)
Since you use the term utility method, I'd say create a static class with the static method and be done with it.
can use extension methods...
namespace ExtendMe
{
public interface IDecorate { }
public static class Extensions
{
public static void CommonMethod(this IDecorate o) { /* do stuff */ }
}
public class Blah :IDecorate {}
public class Widget : IDecorate {}
class Program
{
static void Main(string[] args)
{
new Blah().CommonMethod();
new Widget().CommonMethod();
}
}
}

How to handle static fields that vary by implementing class

I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).
I define an interface ICommand
I create an abstract base class CommandBase which implements ICommand, to contain common code.
I create several implementation classes, each extending the base class (and by extension the interface).
Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...
For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:
public abstract static const string Name;
However (sadly) you cannot define static members in an interface.
I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.
UPDATE:
I can't get the code formatting to work properly (Safari/Mac?). Apologies.
The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).
I forgot to mention - ideally I want to be able to query this information statically:
string name = CommandHelp.Name;
2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.
You may consider to use attributes instead of fields.
[Command("HELP")]
class HelpCommand : ICommand
{
}
As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you can do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:
public abstract class MyBaseClass
{
public abstract string Name { get; protected set; }
}
public class MyClass : MyBaseClass
{
public override string Name
{
get { return "CommandName"; }
protected set { }
}
}
(Note that the protected set prevents outside code changing the name.)
This may not be exactly what you're looking for, but it's as close as I think you can get. By definition, static fields do not vary; you simply can't have a member that is both static and overridable for a given class.
public interface ICommand {
String getName();
}
public class RealCommand implements ICommand {
public String getName() {
return "name";
}
}
Simple as that. Why bother having a static field?
Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like David B suggestion). What if someone extends the abstract class and forget to initiate the field?
just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name
What I usually do (in pseudo):
abstract class:
private const string nameConstant = "ABSTRACT";
public string Name
{
get {return this.GetName();}
}
protected virtual string GetName()
{
return MyAbstractClass.nameConstant;
}
----
class ChildClass : MyAbstractClass
{
private const string nameConstant = "ChildClass";
protected override string GetName()
{
return ChildClass.nameConstant;
}
}
Of course, if this is a library that other developers will use, it wouldn't hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception "Not Implemented".
My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:
interface A { abstract static NAME }
class B { NAME = "HELP" }
class C { NAME = "PRINT" }
Then how could this code know which NAME to link to:
void test(A a) {
a.NAME;
}
How I would suggest to implement this, is one of the following ways:
Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.
The base class has a constructor which takes name
Use annotations and enforce their presence through the base class.
However, a much better solution is proabably to use enums:
public enum Command {
HELP { execute() }, PRINT { execute() };
abstract void execute();
}
This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.
[Suggested answer # 3 of 3]
I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:
[CammandAttribute(Name="HELP")]
Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.
From a design perspective, I think it is wrong to require a static implementation member... The relative deference between performance and memory usage between static and not for the example string is minimal. That aside, I understand that in implementation the object in question could have a significantly larger foot print...
The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited... Only properties and methods are available at the interface level.
The next design challenge is whether the code will be base or implementation specific. With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations. With base your valdiation will occur at run time but logic would be centralized in one place. Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.
So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing. Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization. I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time. All IDE's I work with make this very quick any easy. For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.
Circling back to the very specific nature of the question and ignoring many of the other design problems... If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem... Definately go with a method over properties, as there are way to many side effects to make go use of properties. Use a static member on the base class and use a static constructor on the implementations to set the name. Now keep in mind that you have to valdiate the name at run-time and not compile time. Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name. It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user. Or you could use reflection to get the implementation name and try to generate a name... The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...
For that matter you could always generate the name from the class name thru reflection... Though in the long term this could be a nightmare to maintain... It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns. Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.
What about something like this:
abstract class Command {
abstract CommandInfo getInfo();
}
class CommandInfo {
string Name;
string Description;
Foo Bar;
}
class RunCommand {
static CommandInfo Info = new CommandInfo() { Name = "Run", Foo = new Foo(42) };
override commandInfo getInfo() { return Info; }
}
Now you can access the information statically:
RunCommand.Info.Name;
And from you base class:
getInfo().Name;
[Suggested solution #1 of 3]
Define an abstract property Name in the interface to force all implementing classes to implement the name property.
(in c#) Add this property as abstract in the base class.
In the implementations implement like this:
public string Name
{
get {return COMMAND_NAME;}
}
Where name is a constant defined in that class.
Advantages:
Name itself defined as a constant.
Interface mandates the property be created.
Disadvantages:
Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?
[Suggested solution #2 of 3]
Make a private member variable name.
Define an abstract property Name in the interface.
Implement the property in the base class like this:
public string Name
{
get {return Name;}
}
Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:
public abstract class CommandBase(string commandName) : ICommand
{
name = commandName;
}
Now all my implementations set the name in the constructor:
public class CommandHelp : CommandBase(COMMAND_NAME) {}
Advantages:
My accessor code is centralised in the base class.
The name is defined as a constant
Disadvantages
Name is now an instance variable -
every instance of my Command classes
makes a new reference rather than
sharing a static variable.

Categories