CJC
CJC

Reputation: 817

Method with Generic Type, set value

I have a method which is something like below and i want to set the value of it with input string.

How would i go about it? Any advice will be greatly appreciated

private static void QueueCheckNAdd<T>(ref T param, string input)
    {
        param.DoSomethingLikeSetValue(input);
    }

for your reference, the generic type is something like int or double

Upvotes: 4

Views: 8148

Answers (3)

Gonzague Defraiteur
Gonzague Defraiteur

Reputation: 119

Good practice would be to use interface like described before,

But if you want some fun, you could aslo use the object as a dynamic object, like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class SMTHG
    {
        public void DoSomethingLikeSetValue(string input)
        {
            Console.WriteLine("HEYYYYY!!! DYNAMIC OBJECTS FTW!...\n" + input);
        }
    }
    class Program
    {
        private static void QueueCheckNAdd<T>(ref T param, string input)
        {
            dynamic dynamicObject = (dynamic)param; 
            dynamicObject.DoSomethingLikeSetValue(input);
        }
        static void Main(string[] args)
        {
            SMTHG smthg = new SMTHG();
            QueueCheckNAdd(ref smthg, "yoyuyoyo");
        }
    }
}

Upvotes: 1

Ethan Brown
Ethan Brown

Reputation: 27292

You want param to be generic (i.e., any type), and you expect to be able to call some method on it, correct? Well, you can see the problem there: if param can be any type, there's no way to guarantee that it will have the method DoSomethingLikeSetValue (or whatever). I'm sure you could get fancy with introspection or runtime type coercion, but I think the "clean" way to do what you're looking for is to constrain the type of T to some interface that has the required method (DoSomethingLikeSetValue). Like this:

private static void QueueCheckNAdd<T>(ref T param, string input) where T : IHasSomething {
    param.DoSomethingLikeSetValue(input);
}

public interface IHasSomething {
    void DoSomethingLikeSetValue(string s);
}

Then you can invoke QueueCheckNAdd generically only if the generic type supports the IHasSomething interface. So you could use it like this:

public class Foo : IHasSomething {
    public void DoSomethingLikeSetValue(string s) {
        Console.WriteLine(s);
    }
}

var f = new Foo();
QueueCheckNAdd<Foo>(f, "hello");

Upvotes: 2

SLaks
SLaks

Reputation: 888273

param = (T)(object)Convert.ChangeType(input, typeof(T));

The casts are necessary to convince the compiler that the result is really of type T.

Upvotes: 11

Related Questions