Why does the C# dictionary not call the hidden GetHashCode method - c#

I've a project where I am extensively using the generic C# dictionary. I require composite keys, so I've been using tuples as keys. At some point I was wondering whether it would be beneficial to use a custom class which caches the hash code:
public class CompositeKey<T1, T2> : Tuple<T1, T2>
{
private readonly int _hashCode;
public CompositeKey(T1 t1, T2 t2) : base(t1, t2)
{
_hashCode = base.GetHashCode();
}
public new int GetHashCode()
{
return _hashCode;
}
}
I used new instead of override because I thought it would not make a difference for this test, since I was defining the dictionary using the concrete type:
var dict = new Dictionary<CompositeKey<string, int>, int>();
I noticed, however, that my custom GetHashCode method is not called at all. When I changed new to override it got called as expected.
Can somebody explain why the hidden GetHashCode method is not called? I would expect this behavior if I would define the dictionary like this
var dict = new Dictionary<Tuple<string, int>, int>();
but not if I specify the CompositeKey type explicitly as in my example.
P.S. I know that hiding the GetHashCode method is probably not a good idea.

Can somebody explain why the hidden GetHashCode method is not called?
I would expect this behavior if I would define the dictionary like
this
To be able to call CompositeKey.GetHashCode method, one must have the reference of the instance of CompositeKey typed as CompositeKey in compile time.
But codebase of Dictionary<TKey,TValue> isn't aware of your CompositeKey class(obviously). All it knows is TKey(generic type parameter) which is as equivalent as having System.Object without any constraints. Because you can't call any methods of T other than which is declared in System.Object without a constraint.
So, Dictionary ends up calling Object.GetHashCode which isn't overridden in your class --and thus it is not called.

The overload resolution for method calls in generic types happens when the unbound generic type (e.g. Dictionary<TKey, TValue>) is compiled, not when a closed type (e.g. Dictionary<CompositeKey<string, int>, int>) is constructed.
Since there is no constraint on TKey in Dictionary<,>, the only overload of GetHashCode() available is object.GetHashCode(). Constructing a type where there is a better overload of GetHashCode() doesn't change the initial overload resolution.
It is not only restricted to methods hidden with new. The same happens with overloaded methods:
class Generic<T>
{
public bool Equal(T t1, T t2)
{
return t1.Equals(t2);
}
}
class X : IEquatable<X>
{
public override bool Equals(object obj)
{
Console.WriteLine("object.Equals");
return true;
}
public bool Equals(X other)
{
Console.WriteLine("IEquatable.Equals");
return true;
}
}
The X.Equals(X) overload will never be used
var test = new Generic<X>();
test.Equal(new X(), new X());
// prints "object.Equals"

Just to elaborate on the previous answers. The problem with new is that it ONLY overrides the method IF the consumer is directly operating on the class (in this case your CompositeKey class.) Any call on any base class that your CompositeKey derives from will NOT call your new member.
So if in the following:
CompositeKey.GetHashCode() <--- Will call your new method.
Tuple.GetHashCode() <--- Will not call your new method.
Object.GetHashCode() <--- Will not call your new method.
As previous answers have highlighted, because EqualityComparer (the class Dictionary uses) specifies that T is a non-constrained generic, then the compiler will only support the lowest common denominator for all T that could be passed to it, which is the methods directly on Object.
Therefore the call is effectively: ((Object)key).GetHashCode(). From above you can see that this will not call your new method.

It is because of the type constraints on generics. Here is a simplified program to show the problem.
public class Program
{
public static void Main(string[] args)
{
var bar = new Bar();
TestMethod(bar);
TestMethod2(bar);
}
public static void TestMethod<T>(T obj) where T : Foo
{
obj.Test();
obj.Test2();
}
public static void TestMethod2<T>(T obj) where T : Bar
{
obj.Test();
obj.Test2();
}
}
public class Foo
{
public virtual void Test()
{
Debugger.Break();
}
public virtual void Test2()
{
Debugger.Break();
}
}
public class Bar : Foo
{
public new void Test()
{
Debugger.Break();
}
public override void Test2()
{
Debugger.Break();
}
}
In TestMethod() you hit the breakpoint in Foo.Test() and Bar.Test2() but in TestMethod2() you hit the breakpoint in Bar.Test() and Bar.Test2(), this is because in the first method you are constrained to type Foo or lower so when the compiler compiles it binds to the call on Foo, it is the same as if the function was written as
public static void TestMethod<T>(T obj)
{
((Foo)obj).Test(); //You would expect this to call Foo.Test() b\c of shadowing
((Foo)obj).Test2(); //You would expect this to call Bar.Test2() b\c of overloading
}
Now, on to your problem, the comparer that is being used is written as
[Serializable]
internal class ObjectEqualityComparer<T>: EqualityComparer<T>
{
[Pure]
public override bool Equals(T x, T y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
public override int GetHashCode(T obj) {
if (obj == null) return 0;
return obj.GetHashCode();
}
//...
}
There is no constraint on T so those two methods are behaving as if they are written as
public override bool Equals(T x, T y) {
if (x != null) {
if (y != null) return ((object)x).Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
public override int GetHashCode(T obj) {
if (obj == null) return 0;
return ((object)obj).GetHashCode();
}
That is why your function is only called when you overrode it and not when you shadowed it.

Related

C# Generics Specialization

I created a specialization for a generic like code below:
public class BaseGeneric<T>
{
public static T DoStuff()
=> default;
}
public class SpecializedFromBaseGeneric : BaseGeneric<int>
{
public static new int DoStuff()
=> 789;
}
Now to call the DoStuff() method I would like to use var result = BaseGeneric<int>.DoStuff();
When I run this code, result is 0 instead of 789. The debugger shows that the call will enter the DoStuff() from public class BaseGeneric<T> instead of SpecializedFromBaseGeneric.
What am I doing wrong?
Later edit
I also tried to create specialization in the below format but that does not even compile:
public class BaseGeneric<T> where T : int
{
public static T DoStuff()
=> 789;
}
I want to do several specializations and use the call similar to the one specified above for int data type BaseGeneric<int>.DoStuff(). And for each specialization use the same syntax where only data type is changed but different implementation is used (eg: for string that would be BaseGeneric<string>.DoStuff()). How to achieve this behaviour?
public class BaseGeneric<T> where T : IConvertible
{
public static T DoStuff()
{
if (typeof(T) == typeof(int))
{
return (T)(object)789;
}
if (typeof(T) == typeof(string))
{
return (T)(object)"ss";
}
return default(T);
}
}
However, as the asnwer here suggests, this is brittle, and doesn't cover every possible usage.
var result = BaseGeneric<int>.DoStuff()
This one calls the function of a base class. It returns new T(), that equals new int(), that equals zero.
var result = SpecializedFromBaseGeneric.DoStuff()
This one will return what you need.

HashSet with a custom struct allocates heavy with Contains function

I am using the HashSet collection type which has already significantly improved the performance of my algorithm. It seems that each time I invoke myHashSet.Contains(someValue) the internal implementation is boxing the value type immediately before invoking Equals.
Is there a way to avoid these wasteful allocations when using value types?
Sample Code:
public struct TestStruct {
public int a;
public int b;
public override int GetHashCode() {
return a ^ b;
}
public override bool Equals(object obj) {
if (!(obj is TestStruct))
return false;
TestStruct other = (TestStruct)obj;
return a == other.a && b == other.b;
}
}
var hashset = new HashSet<TestStruct>();
PopulateSet(hashset);
// About to go crazy on the allocations...
if (hashset.Contains(someValue)) { ... }
// Lots of allocations just happened :(
After a lucky guess it looks like the answer is just to implement the IEquatable<T> interface like demonstrated below. HashSet<T> (or at least the Mono implementation) then takes an allocation-free approach to its Contains method by using a different comparer implementation.
public struct TestStruct : IEquatable<TestStruct> {
...
public bool Equals(TestStruct other) {
return a == other.a && b == other.b;
}
}
// No more pain!
if (hashset.Contains(someValue)) { ... }

Get MethodInfo for any method with any signature (delegate for any signature)

I want to write a method that will analyze custom attributes of any method (with any number of arguments and any return type) knowing only method info.
This function will check if method has specific Attribute. like this: var tmp = methodInfo.GetCustomAttributes(typeof(LineItemAttribute),false); and if it has such attribute It will execute it.And I want to make call of that function really easy to use. So, in example there are three methods and method GetMethodAttributes that I want to call.
class Test
{
public static void Main()
{
}
public void Test1(){}
public void Test2(int a){}
public void Test3(object a, string c, Boolean d);
public void GetMethodAttributes(MethodInfo mi) {}
}
Ideally I want to write something like that
public static void Main()
{
var t = new Test();
GetMethodAttributes(t.Test1);
GetMethodAttributes(t.Test2);
GetMethodAttributes(t.Test3);
}
I don't want to use string representation of the method names as method names may change, like that:
MethodInfo info = type.GetMethod(name);
Do I have any options? Basically I need a way to use delegates for functions with different sinatures
As Chris Sinclair pointed out in the comment above; you can use a delegate without using reflection or expression trees to get the MethodInfo. The downside is that the compiler is not able to infer the generic parameter so you have to specify the delegate type to match the signature of the given method like this:
public class Test
{
public static void Main()
{
var t = new Test();
CheckMethodAttributes<Action>(t.Test1);
CheckMethodAttributes<Action<int>>(t.Test2);
CheckMethodAttributes<Action<object, string, bool>>(t.Test3);
}
public void Test1() { }
public void Test2(int a) { }
public void Test3(object a, string c, bool d) { }
public static void CheckMethodAttributes<T>(T func)
{
MethodInfo method = new MethodOf<T>(func);
// Example attribute check:
var ignoreAttribute = method.GetAttribute<IgnoreAttribute>();
if (ignoreAttribute != null)
{
// Do something here...
}
}
}
This uses two utility classes, the MethodOf<T> for extracting the MethodInfo from the given Delegate and some AttributeUtils to get strongly typed custom attribute retrieval:
public static class AttributeUtils
{
public static bool HasAttribute<TAttribute>(this MemberInfo member, bool inherit = true)
where TAttribute : Attribute
{
return member.IsDefined(typeof(TAttribute), inherit);
}
public static TAttribute GetAttribute<TAttribute>(this MemberInfo member, bool inherit = true)
where TAttribute : Attribute
{
return member.GetAttributes<TAttribute>(inherit).FirstOrDefault();
}
public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this MemberInfo member, bool inherit = true)
where TAttribute : Attribute
{
return member.GetCustomAttributes(typeof(TAttribute), inherit).Cast<TAttribute>();
}
}
public class MethodOf<T>
{
public MethodOf(T func)
{
var del = func as Delegate;
if (del == null) throw new ArgumentException("Cannot convert func to Delegate.", "func");
Method = del.Method;
}
private MethodInfo Method { get; set; }
public static implicit operator MethodOf<T>(T func)
{
return new MethodOf<T>(func);
}
public static implicit operator MethodInfo(MethodOf<T> methodOf)
{
return methodOf.Method;
}
}
You can do something like this using Expression Trees, where you pass the method via a lambda expression. You do still need to pass stub values for the parameters, however. For a good example of this in action, check out the source code for Moq, which uses this pattern extensively for setting up mock behaviors for unit testing. Just note that this is not a trivial thing to set up. If you need something relatively quick and dirty, your best bet is probably string names with a good refactoring tool and/or automated tests to help deal with the renaming issues.

Detect if a method was overridden using Reflection (C#)

Say I have a base class TestBase where I define a virtual method TestMe()
class TestBase
{
public virtual bool TestMe() { }
}
Now I inherit this class:
class Test1 : TestBase
{
public override bool TestMe() {}
}
Now, using Reflection, I need to find if the method TestMe has been overriden in child class - is it possible?
What I need it for - I am writing a designer visualizer for type "object" to show the whole hierarchy of inheritance and also show which virtual methods were overridden at which level.
Given the type Test1, you can determine whether it has its own implementation declaration of TestMe:
typeof(Test1).GetMethod("TestMe").DeclaringType == typeof(Test1)
If the declaration came from a base type, this will evaluate false.
Note that since this is testing declaration, not true implementation, this will return true if Test1 is also abstract and TestMe is abstract, since Test1 would have its own declaration. If you want to exclude that case, add && !GetMethod("TestMe").IsAbstract
I was unable to get Ken Beckett's proposed solution to work. Here's what I settled on:
public static bool IsOverride(MethodInfo m) {
return m.GetBaseDefinition().DeclaringType != m.DeclaringType;
}
There are tests in the gist.
As #CiprianBortos pointed out, the accepted answer is not complete and will lead to a nasty bug in your code if you use it as-is.
His comment provides the magic solution GetBaseDefinition(), but there's no need to check the DeclaringType if you want a general-purpose IsOverride check (which I think was the point of this question), just methodInfo.GetBaseDefinition() != methodInfo.
Or, provided as an extension method on MethodInfo, I think this will do the trick:
public static class MethodInfoUtil
{
public static bool IsOverride(this MethodInfo methodInfo)
{
return (methodInfo.GetBaseDefinition() != methodInfo);
}
}
A simple solution which will also work for protected member and properties is as follows:
var isDerived = typeof(Test1 ).GetMember("TestMe",
BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.DeclaredOnly).Length == 0;
This is a repost of my answer here, which in turn had made references to this question.
A method that also works in some non trivial cases:
public bool Overrides(MethodInfo baseMethod, Type type)
{
if(baseMethod==null)
throw new ArgumentNullException("baseMethod");
if(type==null)
throw new ArgumentNullException("type");
if(!type.IsSubclassOf(baseMethod.ReflectedType))
throw new ArgumentException(string.Format("Type must be subtype of {0}",baseMethod.DeclaringType));
while(type!=baseMethod.ReflectedType)
{
var methods=type.GetMethods(BindingFlags.Instance|
BindingFlags.DeclaredOnly|
BindingFlags.Public|
BindingFlags.NonPublic);
if(methods.Any(m=>m.GetBaseDefinition()==baseMethod))
return true;
type=type.BaseType;
}
return false;
}
And a few ugly tests:
public bool OverridesObjectEquals(Type type)
{
var baseMethod=typeof(object).GetMethod("Equals", new Type[]{typeof(object)});
return Overrides(baseMethod,type);
}
void Main()
{
(OverridesObjectEquals(typeof(List<int>))==false).Dump();
(OverridesObjectEquals(typeof(string))==true).Dump();
(OverridesObjectEquals(typeof(Hider))==false).Dump();
(OverridesObjectEquals(typeof(HiderOverrider))==false).Dump();
(OverridesObjectEquals(typeof(Overrider))==true).Dump();
(OverridesObjectEquals(typeof(OverriderHider))==true).Dump();
(OverridesObjectEquals(typeof(OverriderNothing))==true).Dump();
}
class Hider
{
public virtual new bool Equals(object o)
{
throw new NotSupportedException();
}
}
class HiderOverrider:Hider
{
public override bool Equals(object o)
{
throw new NotSupportedException();
}
}
class Overrider
{
public override bool Equals(object o)
{
throw new NotSupportedException();
}
}
class OverriderHider:Overrider
{
public new bool Equals(object o)
{
throw new NotSupportedException();
}
}
class OverriderNothing:Overrider
{
}
According to this answer there could also be a simple way to check if a virtual method was overridden without to know the exact derived or base type using a test for the MethodAttributes.NewSlot attribute:
public static bool HasOverride(this MethodInfo method)
{
return (method.Attributes & MethodAttributes.Virtual) != 0 &&
(method.Attributes & MethodAttributes.NewSlot) == 0;
}
Together with another extension method
private const BindingFlags Flags = BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Instance;
public static bool HasOverride(this Type type, string name, params Type[] argTypes)
{
MethodInfo method = type.GetMethod(name, Flags, null, CallingConventions.HasThis,
argTypes, new ParameterModifier[0]);
return method != null && method.HasOverride();
}
you could then simply call
bool hasOverride = GetType().HasOverride(nameof(MyMethod), typeof(Param1Type),
typeof(Param2Type), ...);
to check if MyMethod is overridden in a derived class.
As far as I've tested this, it seemed to work fine (on my machineā„¢).
There is a better, safer and faster way to do it.
This technique makes sense if your class instance is going to have a long life and the IsOverridden check must be performed several times.
To solve this problem we can use a cache and C# delegates, much faster than reflection!
// Author: Salvatore Previti - 2011.
/// <summary>We need a delegate type to our method to make this technique works.</summary>
delegate int MyMethodDelegate(string parameter);
/// <summary>An enum used to mark cache status for IsOverridden.</summary>
enum OverriddenCacheStatus
{
Unknown,
NotOverridden,
Overridden
}
public class MyClassBase
{
/// <summary>Cache for IsMyMethodOverridden.</summary>
private volatile OverriddenCacheStatus pMyMethodOverridden;
public MyClassBase()
{
// Look mom, no overhead in the constructor!
}
/// <summary>
/// Returns true if method MyMethod is overridden; False if not.
/// We have an overhead the first time this function is called, but the
/// overhead is a lot less than using reflection alone. After the first time
/// this function is called, the operation is really fast! Yeah!
/// This technique works better if IsMyMethodOverridden() should
/// be called several times on the same object.
/// </summary>
public bool IsMyMethodOverridden()
{
OverriddenCacheStatus v = this.pMyMethodOverridden;
switch (v)
{
case OverriddenCacheStatus.NotOverridden:
return false; // Value is cached! Faaast!
case OverriddenCacheStatus.Overridden:
return true; // Value is cached! Faaast!
}
// We must rebuild cache.
// We use a delegate: also if this operation allocates a temporary object
// it is a lot faster than using reflection!
// Due to "limitations" in C# compiler, we need the type of the delegate!
MyMethodDelegate md = this.MyMethod;
if (md.Method.DeclaringType == typeof(MyClassBase))
{
this.pMyMethodOverridden = OverriddenCacheStatus.NotOverridden;
return false;
}
this.pMyMethodOverridden = OverriddenCacheStatus.Overridden;
return true;
}
/// <summary>Our overridable method. Can be any kind of visibility.</summary>
protected virtual int MyMethod(string parameter)
{
// Default implementation
return 1980;
}
/// <summary>Demo function that calls our method and print some stuff.</summary>
public void DemoMethod()
{
Console.WriteLine(this.GetType().Name + " result:" + this.MyMethod("x") + " overridden:" + this.IsMyMethodOverridden());
}
}
public class ClassSecond :
MyClassBase
{
}
public class COverridden :
MyClassBase
{
protected override int MyMethod(string parameter)
{
return 2011;
}
}
class Program
{
static void Main(string[] args)
{
MyClassBase a = new MyClassBase();
a.DemoMethod();
a = new ClassSecond();
a.DemoMethod();
a = new COverridden();
a.DemoMethod();
Console.ReadLine();
}
}
When you run this program as a console application, it will print:
MyClassBase result:1980 overridden:False
ClassSecond result:1980 overridden:False
COverridden result:2011 overridden:True
Tested with Visual Studio 2010, C# 4.0.
Should work also on previous versions, but it can be a little slower on C# less than 3.0 due to optimizations to delegates in the new releases, tests about this would be appreciated :)
However it will be still faster than using reflection!
public static bool HasOverridingMethod(this Type type, MethodInfo baseMethod) {
return type.GetOverridingMethod( baseMethod ) != null;
}
public static MethodInfo GetOverridingMethod(this Type type, MethodInfo baseMethod) {
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod;
return type.GetMethods( flags ).FirstOrDefault( i => baseMethod.IsBaseMethodOf( i ) );
}
private static bool IsBaseMethodOf(this MethodInfo baseMethod, MethodInfo method) {
return baseMethod.DeclaringType != method.DeclaringType && baseMethod == method.GetBaseDefinition();
}
Simple 1-liner based on this and this answers:
typeof(T).GetMember(nameof("Method")).OfType<MethodInfo>()
.Where(m => m.GetBaseDefinition().DeclaringType != m.DeclaringType);

C# Generic and method

How can I select the good method (I have in the example below show 2 differents way that doesn't work). I was using instead of a variable of type Object with a IF and IS to do the job but I am trying to avoid using Object and boxing/unboxing. So I thought that Generic could do the job but I am stuck here.
Here is a small snippet of code that illustrate my question:
class Program
{
static void Main(string[] args)
{
Parser p = new Parser();
ObjectType1 o1 = new ObjectType1();
p.execute(o1);
Console.Read();
}
}
class Parser
{
public T execute<T>(T obj)
{
/*
if (obj is ObjectType1)
this.action((ObjectType1)obj);
else if (obj is ObjectType2)
this.action((ObjectType2)obj);
*/
this.action(obj);
return obj;
}
private void action(ObjectType1 objectType1)
{
Console.WriteLine("1");
}
private void action(ObjectType2 objectType2)
{
Console.WriteLine("2");
}
}
class ObjectType1
{
}
class ObjectType2
{
}
Update
I do not want interface and class. Sorry. I knew that it's not the goal of the question.
Casting with (ObjectType)obj doesn't work but if you do :
if (obj is ObjectType1)
this.action(obj as ObjectType1);
else if (obj is ObjectType2)
this.action(obj as ObjectType1);
it works... why?
And... I cannot overload for all type the execute method because this method is from an Interface. This is why all need to be called from this method.
No, you can't do this. Generics don't work like C++ templates - the generic method is compiled just once. The only information that the compiler can use for overload resolution is the information it knows about within the generic method, regardless of what code uses it.
As an example to show this, here's a bit of code which may not work how you expect it to:
using System;
class Test
{
static void Main()
{
string x = "hello";
string y = string.Copy(x);
Console.WriteLine(x==y); // Overload used
Compare(x, y);
}
static void Compare<T>(T x, T y) where T : class
{
Console.WriteLine(x == y); // Reference comparison
}
}
It's hard to say the best way to proceed without knowing more about what you want to do.
Have you considered interfaces?
interface IAction
{
void action();
}
class ObjectType1 : IAction
{
void action() {
Console.WriteLine("1");
}
}
class ObjectType2 : IAction
{
void action() {
Console.WriteLine("2");
}
}
class Parser
{
public IAction execute(IAction obj)
{
obj.action();
return obj;
}
}
Edited by OP:
This solution would require to change all Business Logic Object to have this interface. This is really not a thing to do (in my situation). And, in other situation, I always prefer to have clean BusinessObject that doesn't have Interface not related with Business stuff. In my question, I want a solution that is more related with Generic/Object/Delegate method to achieve it. Thx you. This answer won't be accepted.
The class Parser has a lot of private method that are called by the execute method depending of the object type. It needs to redirect to the good method.
The compiler will do this work for you. Just use overloads.
class Parser
{
public ObjectType1 action(ObjectType1 objectType1)
{
Console.WriteLine("1");
return objectType1;
}
public ObjectType2 action(ObjectType2 objectType2)
{
Console.WriteLine("2");
return objectType2;
}
}
class ObjectType1 { }
struct ObjectType2 { }
Then, called with:
Parser p = new Parser();
p.action(new ObjectType1());
p.action(new ObjectType2());
There's no boxing/unboxing, and the appropriate method gets called.
I haven't tried it, but can you do this?
public T execute<T>(T obj)
{
this.action((T)obj);
return obj;
}
(according to comments, doesn't work)
or
public T execute<T>(T obj)
{
this.action(obj as T);
return obj;
}
(according to comments, works)
I know you're concerned about boxing/unboxing, so there could be ValueTypes involved here.
public T execute<T>(T obj)
{
this.action(obj);
return obj;
}
Supposing that action is modifying obj, and also supposing that modification is important to the caller (which is why you're returning the value back to the caller). This code has a nasty pass-by-value defect.
Consider this code:
public int execute(int obj)
{
this.action(obj);
return obj;
}
public void action(int obj)
{
obj = obj + 1;
}
Called in this way.
int x = p.execute(1);
x is 1, not 2.
Generics happens in compile time. It is best used when you want the same code to apply to different types. It is not dynamic, so it won't help you switch between methods depending on input types.
Overloading resolving as in David B's reply works, but also happens during compile time.
The code in your update does the same thing. It casts (after careful checking of types) and then uses overloading to resolve the method.
I feel that you want to switch methods based on runtime input.
You could get a more dynamic behaviour if you used Reflection.
public object execute(object obj)
{
MethodInfo m = typeof(Parser).GetMethod(
"action",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new Type[] { obj.GetType() },
null);
m.Invoke(this, new object[] { obj });
return obj;
}
It is perhaps a little fragile, but it works in the example.
IIRC you can use the "where" clause to allow this
public T execute<T>(T obj) where : /* somthing */
{
}
I always have to Google that one my self so I'll leave it at that.
edit: reading some comments. I would not advise calling type specific code. Rather put that code in a virtual function and call that. The call signature might get long, but that's what auto complete is for.
Koodos to joshua.ewer for finding the man page

Categories