Last active
August 19, 2022 13:58
-
-
Save afreeland/6796800 to your computer and use it in GitHub Desktop.
C#: Reflection - Get Property Type, Switch on Type, Set Property Value
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
public static void SetKey<T>(T obj, TempDataDictionary _tempData) | |
{ | |
System.Type type = typeof(T); | |
// Get our Foreign Key that we want to maintain | |
String foreignKey = _tempData["ForeignKey"].ToString(); | |
// If we do not have a Foreign Key, we do not need to set a property | |
if (String.IsNullOrEmpty(foreignKey)) | |
return; | |
// Get our the value that we need to set our Foreign Key to | |
String value = _tempData[foreignKey].ToString(); | |
// Get our property via reflection so that we can invoke methods against property | |
System.Reflection.PropertyInfo prop = type.GetProperty(foreignKey.ToString()); | |
// Gets what the data type is of our property (Foreign Key Property) | |
System.Type propertyType = prop.PropertyType; | |
// Get the type code so we can switch | |
System.TypeCode typeCode = System.Type.GetTypeCode(propertyType); | |
try | |
{ | |
switch (typeCode) | |
{ | |
case TypeCode.Int32: | |
prop.SetValue(type, Convert.ToInt32(value), null); | |
break; | |
case TypeCode.Int64: | |
prop.SetValue(type, Convert.ToInt64(value), null); | |
break; | |
case TypeCode.String: | |
prop.SetValue(type, value, null); | |
break; | |
case TypeCode.Object: | |
if (propertyType == typeof(Guid) || propertyType == typeof(Guid?)) | |
{ | |
prop.SetValue(obj, Guid.Parse(value), null); | |
return; | |
} | |
break; | |
default: | |
prop.SetValue(type, value, null); | |
break; | |
} | |
return; | |
} | |
catch (Exception ex) | |
{ | |
throw new Exception("Failed to set property value for our Foreign Key"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment