how to handle errors with a c# property setter?

Darren Rose 311 Reputation points
2023-07-03T19:57:51.0066667+00:00

Hi, the below code returns an error in some cases, how can I rewrite it to handle the error and in that case return a default value instead.

The error I get on some machines is

System.ArgumentException: '1 is not a supported code page. Parameter name: codepage'

So in those cases then I would want to return a codepage of 437 instead of the 1 it is returning

 public System.Text.Encoding StandardOutputEncoding { get; set; } = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);

I normally program in VB so confused by C# syntax and not sure best way round this, so opens to learn. Thanks

Developer technologies C#
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2023-07-04T05:15:05.99+00:00

    Did you consider this too?

    public System.Text.Encoding StandardOutputEncoding { get; set; } = GetEncoding( );
    
    static System.Text.Encoding GetEncoding()
    {
        try
        {
            return System.Text.Encoding.GetEncoding( System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage );
        }
        catch( ArgumentException )
        {
            return System.Text.Encoding.GetEncoding( 437 );
        }
        catch( NotSupportedException )
        {
            return System.Text.Encoding.GetEncoding( 437 );
        }
    }
    

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-07-04T00:53:44.7566667+00:00

    Think this might be what you are looking for.

    public class Operations
    {
        private string _name;
    
        public string Name
        {
            get => _name;
            set
            {
                if (!string.Equals(_name, value, StringComparison.Ordinal))
                {
                    try
                    {
                        _name = value;
                    }
                    catch (Exception)
                    {
    
                        // decide what to do
                    }
                }
                
            }
        }
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.