including extension methods within interfaces - c#

When abstracting an interface out from a concrete class, should the interface include the extension methods? The context is specifically for ease-of-unit-testability.

As you describe the case, I would say no. If your extension methods are clearly only useful in the context of your unittest, then keep them as extension methods in your test project.
The alternative would be to move your extension methods into the class (changing them into normal public methods), and include them in the interface. This would make them available to everything that consumes your class, which is not desirable for unittest code.
Extension methods are great for adding functionality to classes you don't have control over or separating out areas of responsibility. This is a classic example of the latter.

If a class depends on SomeOtherClass, and it depends on both instance members and static members of SomeOtherClass, then you could either
Change the static members to instance members that can be a part of the interface
Put the static members in a separate extension class (or some other dependency) so that SomeOtherClass can be replaced with an interface.
By using both instance and static members of the dependency, it effectively becomes two dependencies in one. You're depending on the object (instance members) and on the object's type (static members.)
If the methods are required by the class itself in order to function then they should probably be members of that class. If they are needed in order for other classes to use that class in ways that are outside that class's responsibility (like a method that maps a class to some other class) then I'd separate it out.
If the methods are both - required by the class and required by other classes, then you could separate it into another class that both the original class and other classes can depend on.

By way of example, for the following two classes:
class SomeClass
{
public Prop1 { get; }
public void Method1() { .... }
}
static class SomeExtensions
{
public static ExtensionMethod(SomeClass this sc) { ... }
}
As others have said, when creating the interface, you are limited to the public, non-static members in SomeClass, however, it's also worth modifying the extension method to refer to the interface, rather than the concrete type at the same time:
static class SomeExtensions
{
public static ExtensionMethod(ISomeClass this sc) { ... }
}

No. You have a few problems with this. First, interfaces describe only the signature of public instance methods (i.e. they mayn't have implementations and you mayn't specify a static method in an interface). Extension methods must have an implementation at compile time and they aren't instance methods, they're static methods. Note at this point that according to the documentation
In your code you invoke the extension method with instance method
syntax. However, the intermediate language (IL) generated by the
compiler translates your code into a call on the static method.
In other words, it's not really an instance method (even if you can treat it like one); "under the hood" it's still a static method.
Also, extension methods have to be defined in a static class (see Microsoft's instructions on how to implement an extension method).
Note that you can have an extension method on an interface; there's no requirement that the type you're extending be concrete. For example:
public static class Class2
{
public static void Extension(this ITestInterface test)
{
Console.Out.WriteLine("This is allowed");
}
}
Now when I instantiate a concrete class that implements the ITestInterface interface I can call the extension method on it:
// "Test" is some class that implements the ITestInterface interface
ITestInterface useExtensionMethod = new Test();
useExtensionMethod.Extension();
This could do what you want.

Related

Base class or common class?

for our asp.net web application v 4.0, we are in process of defining a class that contains methods that are common across the application. to achieve this there are 2 Suggestions within our team.. one to create a base class, define the methods in that and derive all the other classes from that base class.. the other one is to create a seperate class (not a base class) and instantiate that common class in other classes when required to access the common methods. Please guide me in identifying the best approach..
I'd only go the base class route if there is a real is-a relationship between the base class and the derived classes. One reason is that a class can only inherit from a single base class. I'd use this relationship in a sensible way. Just sharing some helper methods is not a scenario worth blocking this relationship.
If you want to use some helper methods in several classes, composition is the better way as you describe in the 2nd approach. Instead of creating the objects in the classes, you should think about whether you can inject the instances into the classes (see this link for details on dependency injection), e.g.:
public class HelperClass
{
public virtual void HelperMethod()
{
// ...
}
}
public class ClassThatUsesHelper
{
private readonly HelperClass _helper;
public ClassThatUsesHelper(HelperClass helper)
{
_helper = helper;
}
public void DoSomething()
{
_helper.HelperMethod();
}
}
By injecting the helper class you decouple the classes so that you can substitute the helper class by a different implementation that shares the same interface. ClassThatUsesHelper works with any class that is derived from HelperClass (or HelperClass itself of course). So if you need to decorate the helper method or need a special implementation in some cases, this is possible without any problem.
Using composition also enables you to test the helper methods separately.
However, if it is about very basic helper methods, you might also think about having a static class with static helper methods. Please note that you introduce a strong dependency between the classes and that you cannot adjust the implementation easily.
public static class HelperClass
{
public static void HelperMethod()
{
// ...
}
}
public class ClassThatUsesHelper
{
public void DoSomething()
{
HelperClass.HelperMethod();
}
}
Your question is vague, but if you need a method which all objects in your program will need to have access to, that uses their member variables, then I wold recommend creating an abstract class upon which your objects are based.
If you need a means of performing some sort of calculation from anywhere in your code, just create a public static method in a class meant for the purpose. MyMathClass.InterestingFourierTransform(), for example.

How to have all my classes default functionalities like .ToString method

I want to have all my classes some set of behaviour like all classes in .net (ToString, GetHashCode etc.) have.
But I don't want to create a base class which have these type of functions and inherit all the classes from this base class. By going this way I will lost the liberty of inherting my classes from any other class (since .net support inheritance from only one class).
How .net framework create a class without inherting from base object class but has virtual behaivour in all classes?
We don't write like this
class MyClass : System.Object
{
}
but MyClass gets virtual functions of System.Object.
You do not have to explicitly declare that your class inherits from System.Object because the compiler will enforce that your class derive from System.Object automatically if you do not want to do so manually for it could become very tedious.
You can confirm this yourself by declaring a class in your code and then disassembling the assembly output by the compiler. I declared a class class Person { } and disassembled the output. The following IL was produced
.class public auto ansi beforefieldinit Code.Person
extends [mscorlib]System.Object
If you want to define some common functionality amongst your classes without a base class then you might consider writing an extension method on System.Object
public static class ExtensionMethods
{
public static void DoSomething(this object target)
{
}
}
You could be more explicit yet and define an interface that your classes could implement and then define the extension method for said interface. Because there are no limitiations to how many interfaces you can implement this might mitigate your concerns about multiple inheritance.
To build on ByteBlast's post and address harpo's concern, you could use decorator interfaces with extension methods.
public interface IMyDecorator{}
public interface IMySecondDecorator : IMyDecorator {}
public static class ExtensionMethods
{
public static void Print(this IMyDecorator target)
{
}
public static void Print(this IMySecondDecorator target)
{
}
}
Perhaps what you want to have done can be accomplished with PostSharp? Essentially have the tool replace all classes which inherit from System.Object with an inheritance from your custom class?
It's an interesting question, but I think the answer is, you can't. If you're not willing to use a universal base class, then you cannot provide universal behavior for methods inherited from object.
If this really matters to you, then it's worth considering the base class route. Of course, you can't make it apply to framework classes, but those are sealed (or invisible) in many cases anyway.
I have been thinking about this question because I'm working with a few classes that do nothing but provide GetHashCode and Equals overrides for classes with value-type semantics. In several cases, it would be very handy to use an alternate base class, but you simply cannot override those behaviors by any other means (e.g. interfaces/extension methods).
A universal base class is the obvious answer to this problem but will not provide the 'standard' implementation for classes that inherit from types outside of your application's class hierarchy.
I would consider composition in place of inheritance. This is the essence of what has been proposed by #ByteBlast and #PhilipScottGivens.
Why not have a helper class that provides the functionality for you GetHashCode and ToString methods (I am picturing some reflection in both of these so that you can work with the members / properties of the instances of your types) and whatever other common services you require for all objects?
An instance of this (or maybe the helper has static methods that you pass an instance to - much like the extension methods) is passed into each object or created by the instance of your object.

Static method in abstract class to return IEnumerable<DerivedType>

Is there a way of putting a static method in an abstract class that can return the derived type?
Does a static method even know what type it is even being called from in C#?
For example, a base class could be
public abstract class MyBase
{
public static IEnumerable<TDerivedType> LoadAll()
{
//functionality here
}
}
Then if MyDerivedType inherits MyBase, I'd like to be able to call MyDerivedType.LoadAll()
Nothing too important - I'm currently using a generic static method and calling MyBase.LoadAll<MyDerivedType>(), which works fine but it doesn't look quite as 'pretty' as this would be.
Static members aren't inherited, so the static method has to be told in some way what the derived type is. Your solution is one way. Another is the following:
public abstract class MyBase<T> where T : MyBase<T> {
public static IEnumerable<T> LoadAll() { }
}
Then:
class Derived : MyBase<Derived> { }
var all = MyBase<Derived>.LoadAll();
That said, I think there is something wrong with your model. MyBase represents something in your domain (of which they are more specific derived types) AND it knows how to load all of those objects? That's two responsibilities, and that ain't cool yo.
No, there currently isn't a way to do this. I'd possibly use a factory in this case
var all = MyClassFactory.LoadAll<MyDerivedType>();
An abstract class can never be instantiated(that's the whole point) so any static methods would have to be implemented in each child class.
From an MSDN Thread
Static methods can be defined in an abstract class. However, you cannot force a derived class to implement a static method. If you think about it, such a method would be useless. Static methods are invoked using type names, not instance variables. If I call MyBaseClass.MyMethod, then MyBaseClass.MyMethod will always be invoked. How would it do you any good to force MyChildClass, which inherits from MyBaseClass, to also a implement a static MyMethod?
(Note: edited implemented to instantiated in the first sentence.)
There is nothing wrong with the way you are doing this. In fact most of MS generic extension methods are designed like this.
As for:
"Does a static method even know what type it is even being called from in C#?"
Its not a question of the static method knowing, its a question of the compiler knowing. When the code is scanned by the compiler this is when all the types are consolidated. At this point it can work out what code calls what functions and what types need to be returned. This is also the reason that a var type cannot be returned from a function.

Why can't I inherit static classes?

I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.
But it seems I can't declare inheritance for static classes.
Something like that:
public static class Base
{
}
public static class Inherited : Base
{
}
will not work.
Why have the designers of the language closed that possibility?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).
So this:
static class Foo { }
compiles to this IL:
.class private abstract auto ansi sealed beforefieldinit Foo
extends [mscorlib]System.Object
{
}
Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.
Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.
Perhaps you want to add methods to an existing static type. You can do that already via extension methods.
Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.
So, in the end you don't really gain anything from inheriting static classes.
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:
public class TestClass<T>
{
protected TestClass()
{ }
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public class TestClass : TestClass<double>
{
// Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
protected TestClass()
{ }
}
TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)
// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
Unfortunately because of the "by-design" language limitation we can't do:
public static class TestClass<T>
{
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public static class TestClass : TestClass<double>
{
}
You can do something that will look like static inheritance.
Here is the trick:
public abstract class StaticBase<TSuccessor>
where TSuccessor : StaticBase<TSuccessor>, new()
{
protected static readonly TSuccessor Instance = new TSuccessor();
}
Then you can do this:
public class Base : StaticBase<Base>
{
public Base()
{
}
public void MethodA()
{
}
}
public class Inherited : Base
{
private Inherited()
{
}
public new static void MethodA()
{
Instance.MethodA();
}
}
The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.
There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.
P.S.
We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.
My answer: poor design choice. ;-)
This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.
A pseudo example, assuming static inheritance was defined in some way.
public static class MyStaticBase
{
SomeType AttributeBase;
}
public static class MyStaticChild : MyStaticBase
{
SomeType AttributeChild;
}
would lead to:
// ...
DoSomethingTo(MyStaticBase.AttributeBase);
// ...
which could (would?) impact the same storage as
// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...
Very confusing!
But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.
I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:
public static class MyStaticBase<T>
{
public static T Payload;
public static void Load(StorageSpecs);
public static void Save(StorageSpecs);
public static SomeType AttributeBase
public static SomeType MethodBase(){/*...*/};
}
Then you get:
public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
public static SomeType AttributeChild;
public static SomeType SomeChildMethod(){/*...*/};
// No need to create the PlayLoad, Load(), and Save().
// You, 'should' be prevented from creating them, more on this in a sec...
}
Usage looks like:
// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...
The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.
Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.
I believe the right design choice would be to allow static inheritance with specific limitations:
No override of anything. The child cannot replace the base
attributes, fields, or methods,... Overloading should be ok, as
long as there is a difference in signature allowing the compiler to
sort out child vs base.
Only allow generic static bases, you cannot inherit from a
non-generic static base.
You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.
I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
Following are the main features of a static class:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).
When we create a static class that contains only the static members and a private constructor.The only reason is that the static constructor prevent the class from being instantiated for that we can not inherit a static class .The only way to access the member of the static class by using the class name itself.Try to inherit a static class is not a good idea.
I run into the problem when trying to code an IComparer<T> implementation against a third-party library where T is an enum embedded in a class as in the following:
public class TheClass
{
public enum EnumOfInterest
{
}
}
But because the enum is defined within a third-party library class, I can't write the comparer because the following gives a "cannot extends list" error:
public class MyComparer : IComparer<TheClass.EnumOfInterest>
{
}
I'm not even extending a static class -- I'm just implementing a comparer of a enum defined in a class.

C#: How do I call a static method of a base class from a static method of a derived class?

In C#, I have base class Product and derived class Widget.
Product contains a static method MyMethod().
I want to call static method Product.MyMethod() from static method Widget.MyMethod().
I can't use the base keyword, because that only works with instance methods.
I can call Product.MyMethod() explicitly, but if I later change Widget to derive from another class, I have to revise the method.
Is there some syntax in C# similar to base that allows me to call a static method from a base class from a static method of a derived class?
static methods are basically a method to fallback from object oriented concepts. As a consequence, they are not very flexible in inheritance hierarchies and it's not possible to do such a thing directly.
The closest thing I can think of is a using directive.
using mybaseclass = Namespace.BaseClass;
class MyClass : mybaseclass {
static void MyMethod() { mybaseclass.BaseStaticMethod(); }
}
It can be done, but I don't recommend it.
public class Parent1
{
public static void Foo()
{
Console.WriteLine("Parent1");
}
}
public class Child : Parent1
{
public new static void Foo()
{
Type parent = typeof(Child).BaseType;
MethodInfo[] methods = parent.GetMethods();
MethodInfo foo = methods.First(m => m.Name == "Foo");
foo.Invoke(null, null);
}
}
Calling a static method using reflection is exactly the same as calling an instance method except that you pass null for the instance. You need FlattenHierarchy because it's defined in an ancestor.
var type = assy.GetType("MyNamespace.MyType");
MethodInfo mi = type.GetMethod("MyStaticMethod",
BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
mi.Invoke(null, null);
Further reading and thinking leaves me asking the same questions as others who have responded: why use static methods like this? Are you trying to do functional programming, and if so why not use lambda expressions instead? If you want polymophic behaviours with shared state, instance methods would be better.
It can be done:
public class Parent1
{
protected static void Foo()
{
Console.WriteLine("Parent1");
}
}
public class Child : Parent1
{
public static void Foo()
{
return Parent1.Foo();
}
}
Can be useful for unit testing protected static methods (for example).
First and foremost, if you're worried about re-parenting a class, then you're probably doing inheritance wrong. Inheritance should be used to establish "is-a" relationships, not simply foster code reuse. If you need code re-use alone, consider using delegation, rather than inheritance. I suppose you could introduce an intermediate type between a sub-type and its parent, but I would let that possibility drive my design.
Second, if you need to use functionality from the base class but extend it AND the use case calls for a static method, then you might want to consider using some external class to hold the functionality. The classic case for this in my mind is the Factory pattern. One way to implement the Factory pattern is through Factory Methods, a static method on a class that constructs an instance of that class. Usually the constructor is protected so that the factory method is the only way to build the class from outside.
One way to approach re-use with Factory Methods in an inheritance hierarchy would be to put the common code in a protected method and call that method from the Factory Method rather than directly call the base class Factory Method from a sub-types Factory Method. A better implementation might use the same technique but move the Factory Methods to a Factory class and use the constructor logic (internal now, not private), perhaps in conjunction with an initialization method(s), to create the object. If the behavior you are inheriting is external from the class (decryption/validation/etc), you can use shared methods (or composition) within the Factory to allow re-use between the Factory methods.
Without knowing the goal of your use of static methods it's difficult to give you an exact direction, but hopefully this will help.
Static methods are not polymorphic, so what you want to do is impossible.
Trying to find a way to treat static methods as polymorphic is possible but dangerous, because the language itself doesn't support it.
Some suggestions:
Reflection
Aliasing the base class (such as Mehrdad's example)
Having into account that a Static method shoudn't relay in instance data... you should have a static "MyMethod" that behaves diferent based on a parameter or something like that.
Remember that the static method defined in one class is just a way to order your code... but it is the same if that method is placed elsewhere... because it don't relay on the object where it is placed.
EDIT: I think your best choise is to use Product.MyMethod explicitly... If you think it... it should't be probable that your Widget change its base clase... and also in that case it is a minor change in code.
Static methods are "Class-Level" methods. They are intended to be methods that apply to all instances of a specific class. Thus, inheritance of this method does not make sense as it would change the meaning to apply to instances of the class. For instance, if you were looping through a collection of Products (some of Widget, some not) and called MyMethod on each Product then the method that was called would be determined by the instance of the class. This violates the purpose of static methods.
You can probably do something like you want more cleanly by simply not using static methods at all, because in your example it does not seem like MyMethod applies to all instances of Product. However, you can achieve the same affect you are describing by using an interface class like ‘IMyMethod’. This approach is still not using a static method. I guess I’m not seeing a need for a static method. Why do you want to use a static method to begin with?
It's very simple. Much simpler than using aliasing, reflections, etc. Maybe it's been made easier in newer additions of .NET, IDK, but this works perfectly fine. Just like with instance methods, accessing base methods doesn't require base be used, it is optional, usually necessary when the inheriting and base class have a method of the same name. Even without the base keyword, you can access the static methods of a base class as if they were in the class you are calling from. I only tested this when calling a base static method from a derived class's static method. Might not work if you are calling from an instance method to a static method.
public class BaseThings
{
protected static void AssertPermissions()
{
//something
}
}
public class Person:BaseThings
{
public static void ValidatePerson(Person person)
{
//just call the base static method as if it were in this class.
AssertPermissions();
}
}

Categories

Resources