2

Can anybody help me with refactoring of such methods:

public static void MethodA(this SceneObject obj, double value)
public static void MethodA(this SceneObject obj, long value)
public static void MethodA(this SceneObject obj, int value)

public static void MethodB(this IEnumerable<MyData> sObjects, IEnumerable<int> values)
public static void MethodB(this IEnumerable<MyData> sObjects, IEnumerable<long> values)

How can I make them one generic method that can take any kind of param? Thanks.

3 Answers 3

3

Just use the generic feature.

public static void MethodA<T>(this SceneObject obj, T value)

Then you can use it like this:

SceneObject.MethodA<long>(50);
Sceneobject.MethodA<int>(50);

The value parameter automatically gets the type of T. So in this case long or ìnt.

Sign up to request clarification or add additional context in comments.

Comments

2

If your question just is about how to make your definition generic, it could be done like:

public static void Method<T>(this object, T value)

If you want to be able to use it on all kind of objects or not you may want to adjust the type you are extending.

The usage would then be:

someObject.Method<int>(1);
someObject.Method<long>(1);
someObject.Method<double>(1);

someObject.Method<List<int>>(new List<int> { 1, 2, 3 });

If you would like to have a numeric constraint you could also do something like:

public static void Method<T>(this object, T value) : where T : IComparable, IComparable<T>

Comments

1
public static void MethodA<T>(this SceneObject obj, T value) where T : struct 

public static void MethodB<T>(this IEnumerable<MyData> sObjects, IEnumerable<T> values) where T : struct 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.