Created
February 2, 2023 14:59
-
-
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>.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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