-3

I am writing a generic class in C# 6.0 (VS2015) that has module-level values (fields, properties, etc.) of the generic type. However, I need to include extra methods/code for certain data types (specifically int), but I cannot figure out how assign the int's values/results to the generic-type properties in a way that the compiler will accept.

class FOO<T>
{
    public T yada;

    void BAR(int nom)
    {
        if(nom is T)
        {
            yada = (T)nom;
        }
    }
}

I cannot figure out how to get it to accept that last line: yada = (T)nom;, it always says that it cannot convert nom to T.

I feel like there must be a simple way to do this and I may have even done it before, but I sure cannot remember it now. I have tried to google this extensively, but I must be using the wrong words because all it keeps returning is articles about how to type-constrain the class itself, which isn't what I'm trying to do.

RBarryYoung
  • 55,398
  • 14
  • 96
  • 137

1 Answers1

1

You can simply write:

class FOO<T>
{
  public T yada;

  public void BAR(int nom)
  {
    if ( nom is T )
    {
      yada = (T)(object)nom;
    }
  }
}

Example

var foo = new FOO<int>();
foo.BAR(10);
Console.WriteLine(foo.yada);

Output

10
  • `Convert.ChangeType(..)` is probably what I was thinking of, thanks. However, I am completely perplexed that `(T)(object)nom` would work though. I can see that it does, but it seems crazy. – RBarryYoung Sep 15 '20 at 17:30
  • Yes, my first and quick reaction was to use Convert, but after I saw that we convert int to int here, so no need to do that, only cast to object and next to T. Because int can't be casted to whatever, but object can and type mismatch eventually raises an exception at runtime, but no compiling error. –  Sep 15 '20 at 17:34