Skip to content

Instantly share code, notes, and snippets.

@xepherys
Created February 2, 2023 14:59
Show Gist options
  • Save xepherys/9e3286d0d94b1479b852dd6d806f0aac to your computer and use it in GitHub Desktop.
Save xepherys/9e3286d0d94b1479b852dd6d806f0aac to your computer and use it in GitHub Desktop.
Cast from an object to the target type of a generic in a generic Class<T>.
using System;
public class Program
{
public static void Main()
{
int myInt = 5;
TestValue<float> testValue = new TestValue<float>();
testValue.SetValue(myInt);
testValue.PrintMe();
}
}
public class TestValue<T>
{
T value;
// This is the important bit
public void SetValue(object value)
{
if (value is T)
{
this.value = (T)value;
}
try
{
T val = (T)Convert.ChangeType(value, typeof(T));
this.value = (T)val;
}
catch (InvalidCastException)
{
Console.WriteLine("Nope.");
}
}
public void PrintMe()
{
Console.WriteLine(this.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment