Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8419629
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T02:40:02+00:00 2026-06-10T02:40:02+00:00

I am using the code below to set the values of a class, some

  • 0

I am using the code below to set the values of a class, some values on this class are string decimal decimal? int? etc.

I have a list of fields – with its value as a string, .net is throwing the exception below:

System.InvalidCastException : Invalid cast from 'System.String' to 'System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)
at Surventrix.Domain.Model.Entities.StatisticalData.UpdateStatisticalData(ReportCommit commit, ILogProvider log) in StatisticalData.cs: line 591
at Surventrix.Tests.Stats.StatsTest.CreateStatsFromCommit() in StatsTest.cs: line 32 

my code is:

    public void UpdateStatisticalData(ReportCommit commit, ILogProvider log)
    {
        var fields = commit.CurrentFieldList.ToList();

        var properties = typeof(StatisticalData).GetProperties();

        foreach (var p in properties)
        {
            log.LogMessage("what my name: {0}", p.Name);
            // If not writable then cannot null it; if not readable then cannot check it's value
            if (!p.CanWrite || !p.CanRead) { continue; }

            var mget = p.GetGetMethod(false);
            var mset = p.GetSetMethod(false);

            // Get and set methods have to be public
            if (mget == null) { continue; }
            if (mset == null) { continue; }


            var val = fields.SingleOrDefault(x => p.Name == x.Name);

            if (val == null) continue;

            //field.value is stored as a string
            if (string.IsNullOrEmpty(val.Value)) continue;

            log.LogMessage("set: {0} ----> {1}", p.Name, val.Value);

            var typedVal = Convert.ChangeType(val.Value, p.PropertyType);

            p.SetValue(this, typedVal, null);
        }

    }

Question: how can I fix my code so this exception is not thrown, i dont really understand why this exception is being thrown here…

update – result of log*

what my name: StatisticalDataID
what my name: OfficeDistanceFromProperty
what my name: OfficeAddress1
set: OfficeAddress1 ----> North Warwickshire House
what my name: OfficeAddress2
set: OfficeAddress2 ----> 92 Wheat Street
what my name: OfficeAddress3
what my name: OfficeCounty
what my name: OfficeTown
set: OfficeTown ----> Nuneaton
what my name: OfficePostcode
set: OfficePostcode ----> CV11 4BH
what my name: ResidentialInternalFloorArea
what my name: ValuationCalculationSqFtAssumed
what my name: SubjectPropertyAddress1
set: SubjectPropertyAddress1 ----> 323 Stanton road
what my name: SubjectPropertyAddress2
set: SubjectPropertyAddress2 ----> cbvcb
what my name: SubjectPropertyAddress3
set: SubjectPropertyAddress3 ----> vcbc
what my name: SubjectPropertyTown
set: SubjectPropertyTown ----> Coventry
what my name: SubjectPropertyCounty
set: SubjectPropertyCounty ----> bcbvc
what my name: SubjectPropertyPostCode
set: SubjectPropertyPostCode ----> CV1 4HH
what my name: OccupierName
set: OccupierName ----> Mr Peters
what my name: AdvanceAmount
set: AdvanceAmount ----> 0

Update – I have updated to your code @Jon, I am calling the method like so:

            var typedVal = NullableSafeChangeType(val.Value, p.PropertyType);

            if (!string.IsNullOrEmpty(val.Value))
                p.SetValue(this, typedVal, null);

which throws an error at:

            _log.LogMessage("error is here ---> {0}", input);
            return input == null || input == "" ? null : Convert.ChangeType(input, underlyingType);

The input is any valid string, type(System.String)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T02:40:04+00:00Added an answer on June 10, 2026 at 2:40 am

    It’s got nothing to do with setting the property, and everything to do with changing the type. Here’s a short but complete example demonstrating the problem:

    using System;
    
    class Test
    {
        static void Main()
        {
            object converted = Convert.ChangeType("10", typeof(int?));
            Console.WriteLine(converted);
        }
    }
    

    Basically, Convert.ChangeType doesn’t support Nullable<T>. You’ll have to handle that yourself. You could write a method which detect that the target type is Nullable<T>, and either returns null (if the original string value is null or a reference to an empty string) or the result of converting it to the underlying type.

    EDIT: For example (completely untested):

    static object NullableSafeChangeType(string input, Type type)
    {
        Type underlyingType = Nullable.GetUnderlyingType(type);
        if (underlyingType == null) // Non-nullable; convert directly
        {
            return Convert.ChangeType(input, type);
        }
        else
        {
            return input == null || input == "" ? null
                : Convert.ChangeType(input, underlyingType);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Form contains two dropdown lists created using code below. Both dropdown list elements have
I have tried using the code below but it only display results in Chrome
In the code base I was maintaining I found this exact class, pasted below.
I have some code that works and changes the style sheet using a form.
I have been using some code to create MTOM by using code from MSDN
I can insert a row by using code below. USE pmdb; INSERT INTO md5_tbl
Using the code below I can insert a new row to my table (
Using the code below, I am attempting to fill a Canvas with UIElements and
Using the code below (from a console app I've cobbled together), I add seven
Using the code below, I want to keep the same menu div opened in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.