Home > c# > Is there a better way to convert to a specific type with reflection?

Is there a better way to convert to a specific type with reflection?

July 27Hits:1
Advertisement

Rather than doing what is essentially a large switch statement for every possible type, is there a better more generic way of converting to a specific type with reflection? I've looked up TypeConverter but don't understand the documentation.

if (header.Property.PropertyType == typeof(Int32)) {   header.Property.SetValue(instanceOfTrade, value.ToInt(), null); } else if (header.Property.PropertyType == typeof(decimal)) {   header.Property.SetValue(instanceOfTrade, value.ToDecimal(), null); } else if (header.Property.PropertyType == typeof(DateTime)) {   header.Property.SetValue(instanceOfTrade, value.TryToDateTime(), null); } else {   header.Property.SetValue(instanceOfTrade, value.ToString(), null); } 

Answers

You could use an extension method (if this is common), or a regular generic method with a "IConvertible" constraint on the desired value then call "Convert.ChangeType" in your SetValue call.

static class ObjectExtensions
{
    public static void SetPropertyValue<T>(this object obj, string propertyName, T propertyValue)
        where T : IConvertible
    {
        PropertyInfo pi = obj.GetType().GetProperty( propertyName );

        if( pi != null && pi.CanWrite )
        {
            pi.SetValue
            (
                obj,
                Convert.ChangeType(propertyValue, pi.PropertyType),
                null
            );
        }
    }
}

class TestObject
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

void Main()
{
    TestObject o = new TestObject();

    // Propery1 == null, Property2 == 0
    o.SetPropertyValue( "Property1", 1 );
    o.SetPropertyValue( "Property2", "123" );
    // Propery1 == 1, Property2 == 123
}

Obviously no error handling and this is assuming you want it available on all types, so I just threw it in an "ObjectExtensions" class so it'll be visible on all types.

Just adjust the constraints to fit your exact needs, or just throw it in a regular class if you don't want to use extensions.

Tags:reflection

Related Articles

  • Is there a better way to convert to a specific type with reflection?July 27

    Rather than doing what is essentially a large switch statement for every possible type, is there a better more generic way of converting to a specific type with reflection? I've looked up TypeConverter but don't understand the documentation. if (head

  • VHDL: Converting from an INTEGER type to a STD_LOGIC_VECTORSeptember 21

    I built a mod-16 counter, and the output result is a INTEGER (all the examples I saw used INTEGER). I built a hex-to-7-segment-display decoder, and its input is a STD_LOGIC_VECTOR (wrote it that way because it was easy to map out the truth table). I'

  • How to convert audio file of type G.723.1 into wav format?June 14

    I have few audio files which have .wav extension. I tried to get information about this file using soxi <foo.wav> command but I got following error : soxi FAIL formats: can't open input file foo.wav': Unknown WAV file encoding (type a100) So I used

  • What would break if there was an option to make undefined not convert to any other type in JavaScript?November 11

    The biggest issue I run into in JavaScript is silent typos. For example, the other day I had a variable inIframe. Somewhere else I typed isIFrame. 10-15 mins of debugging later I found it and changed it to inIFrame. It was yet another 5+ mins until I

  • Cannot convert return expression of type 'UIColor' to return type '[UIColor]' on UIColor extensionJanuary 19

    I'm writing a simple extension for UIColor to take a hex string based off this answer: import UIKit extension UIColor { public static func colorWithString (hex:String) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterS

  • how to convert long raw data type to readable format(oracle version :11.2.0.3.0) in oracle?February 8

    how to convert long raw data type to readable format(oracle version :11.2.0.3.0) in oracle? Please help me oracle version :11.2.0.3.0 i want to convert long raw data type to readable format --------------Solutions------------- I use this code from Ad

  • How can I convert Posts into Custom type posts?March 15

    I have a Wordpress site that I just updated to 3.1. I want to make use of custom post types now, my question is how can I assign (transfer?) a post to a newly created custom post type ? For example, all my articles (news, poems, ideas to change the w

  • SQL Performance - Convert parameter or column typeOctober 1

    I was asked this on an interview, and would like some feedback... I have a stored procedure that takes in a varchar parameter IsActive that is either a "YES" or "NO" string. The stored procedure will query a table that has an Active co

  • How to convert Rules 'text' data type to 'text_formatted' type?January 30

    I am working with Rules to set a node's body. Based on the data selector, the node body requires a text_formatted type as input. Currently, my custom event only provides a plain 'text' Rules data type. Is there a way I can programmatically convert th

  • Converting Drupal 7 Content TypesMay 31

    What are the steps needed and modules required to convert a large number of nodes from one content type to another, both in Drupal 7. They are fairly simple. If you know of a good tutorial that would be great too. All my searching seems to bring up m

  • convert string to sObjectfield typeSeptember 3

    I have a custom setting where I have fields api name and getting the field api name and use with sObject. At that time I am getting error cannot use string with the sObject. How can I convert the string to a sObjectField or is there any other way to

  • Should a class own the responsibility of converting an incorrect data type?November 18

    The ElectricalEngine class responds to the horsepower message. Because efficiency is calculated in percent a programmer can mistakenly initialize it with an integer instead of a float. class ElectricalEngine attr_reader :volts, :current, :efficiency

  • Convert from one archive type to another using CLIJanuary 4

    If a particular archive type has to be converted into another format (eg - tar.gz to zip), then one can open the archive using file-roller and go to - Archive -> Save As -> (select the extension) -> Save Also, in this method, Other Options can be

  • Excel Convert the correct Date type

    Excel Convert the correct Date typeMarch 2

    I'm currently following the date type dd/mm/yyyy i need to have another row showing the month in mmm type. E.g. From 13/09/2014 to SEP My formula is =Text(A2, "mmm") which is the correct formula, However it reads the text as mm/dd/yyyy thus havi

  • Arithmetic overflow error converting float to data type numericMarch 19

    I am trying to move data from a csv file into a SQL server database. Some of my values are in the scientific notation. I figured out on how to get most of them converted but for one value I get the Arithmetic overflow error. The value that is causing

  • To convert to accurate data types or maintain default type of stringApril 15

    Scenario: I have a web application that records and checks data against two temp tables (1 table being a temp source and the other being a destination for the application). These temp tables are synced up each night with their respective destination/

  • Optimize a generic foreach method that converts Datatable to my object using ReflectionApril 23

    I need to optimize this code block below, this method converts a Datatable object to the Object that I am passing by parameter, in another words, this serializes the object, however I have to run this block 1 million times when reading data from the

  • Converting images of different types to PDF November 20

    This question already has an answer here: Create a single pdf from multiple text, images or pdf files 5 answers I have a few hundred image files. This consist of files of multiple type like 1.png 2.jpg 3.png and so on. I want to create a PDF from the

  • Converting column with data type string to double using ModelBuilder?January 5

    I am using ModelBuilder to create a tool. In the middle I have to convert the string values of two columns of a data (in attribute table) to double (for calculations in later steps). Can I do this using ModelBuilder itself rather than doing it manual

  • Can you statically assert that object can be converted to a certain type?January 14

    I'm currently working on a console GUI library for C++11 just to ease some debugging and stuff. For a certain class that templates, I want to make sure I can convert the templated type to string before I print it. Example: template<typename T> class

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.966 s.