-1

It seems that if there is only one parameter of type array on a method the value of the parameter passed to my LogException() method is not an array anymore.

When there is more than one parameter on a method, or if the one parameter is not an array, it works as expected. But when I try to pass an array, it seems that the first value of the array becomes the parameter that was passed.

All comments are inlined to explain and show the problem. The problem first appears at "point 4"; once the wrong value is found, the parameter information being stored in my exception is wrong. The other points clarify the subsequent confusion that arises. I have no idea how solve it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Testapp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] tmp1 = new string[2];
            tmp1[0] = "val1";
            tmp1[1] = "val2";

            //please look at point 1
            TestMethod1(tmp1);
            //please look at point 2
            TestMethod2(tmp1, "just a value");
        }


        private static void TestMethod1(string[] ArrayType)
        {
            try
            {
                throw new System.Exception("blow");
            }
            catch (System.Exception ex)
            {
                LogException(ex, ArrayType);

                foreach (System.Collections.DictionaryEntry entry in ex.Data)
                {
                    string tmp1 = entry.Key.ToString();
                    string tmp2 = entry.Value.ToString();
                    //point 1 (for param:ArrayType... well there is only 1 parameter)
                    //the value of tmp2 = val1
                    //and should be {val1,val2}
                    System.Diagnostics.Debugger.Break();
                }
            }
        }
        private static void TestMethod2(string[] ArrayType, string StringType)
        {
            try
            {
                throw new System.Exception("blow");
            }
            catch (System.Exception ex)
            {
                LogException(ex, ArrayType, StringType);

                foreach (System.Collections.DictionaryEntry entry in ex.Data)
                {
                    string tmp1 = entry.Key.ToString();
                    string tmp2 = entry.Value.ToString();

                    //point 2 (for param:ArrayType)
                    //the value of tmp2 = {val1,val2} (correct, this what i expected)
                    //please look at point 3
                    System.Diagnostics.Debugger.Break();
                }
            }
        }

        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
        public static void LogException(System.Exception Exception, params object[] args)
        {
            using (CallerInfo callerinfo = new CallerInfo(1))
            {
                callerinfo.AddParameterInfo(Exception, args);
            }
        }

        private class CallerInfo : IDisposable
        {
            private System.Reflection.ParameterInfo[] parameterinfos = null;
            private string identifiername = string.Empty;
            private string assemblyname = string.Empty;

            public void AddParameterInfo(System.Exception Exception, params object[] sourceargs)
            {
                if (parameterinfos == null) return;

                string locationname = identifiername + " - param:";
                foreach (System.Reflection.ParameterInfo ParameterInfo in parameterinfos)
                {
                    string KeyName = locationname + ParameterInfo.Name;
                    object parameter = null;
                    try
                    {
                        System.Diagnostics.Debugger.Break();
                        //point 4
                        //the next line goes wrong when there is ONLY 1 parameter on a method of type array
                        parameter = sourceargs[ParameterInfo.Position];

                    }
                    catch
                    {
                        parameter = null;
                    }
                    if (parameter == null)
                    {

                        if (!Exception.Data.Contains(KeyName))
                        {
                            Exception.Data.Add(KeyName, "*NULL*");
                        }
                    }
                    else
                    {
                        if (ParameterInfo.ParameterType.IsArray)
                        {
                            //point 3
                            //this is where i got confused
                            //the check if (ParameterInfo.ParameterType.IsArray) is returning true.. correct the first parameter in both methods are of type array
                            //however for TestMethod1 (that is having ONLY 1 parameter) the value of parameter (see point 4) is NOT an array anymore?????
                            //for TestMethod2 (that is having 2 parameters, but the SAME first parameter as passed in TestMethod1) the value of parameter (see point 4) is an array what is correct
                            System.Diagnostics.Debugger.Break();
                            if (parameter.GetType().IsArray)
                            {
                                string arrayvaluelist = "{";
                                try
                                {
                                    System.Collections.ArrayList arraylist = new System.Collections.ArrayList((System.Collections.ICollection)parameter);
                                    foreach (object arrayitem in arraylist)
                                    {
                                        if (arrayitem == null) { arrayvaluelist = arrayvaluelist + "*NULL*,"; continue; }
                                        arrayvaluelist = arrayvaluelist + arrayitem.ToString() + ",";
                                    }
                                    arrayvaluelist = arrayvaluelist.Substring(0, arrayvaluelist.Length - 1);
                                    arrayvaluelist = arrayvaluelist + "}";
                                }
                                catch
                                {
                                    arrayvaluelist = "Error in constructing the arrayvalue list for parameter: " + ParameterInfo.Name;
                                }
                                if (!Exception.Data.Contains(KeyName))
                                {
                                    Exception.Data.Add(KeyName, arrayvaluelist);
                                }
                            }
                            else
                            {
                                //point 5 -- i shouldn't be here !!!!
                                System.Diagnostics.Debugger.Break();
                                if (!Exception.Data.Contains(KeyName))
                                {
                                    Exception.Data.Add(KeyName, parameter.ToString() + " warning wrong value is returned.");
                                }
                            }
                        }
                        else
                        {
                            if (!Exception.Data.Contains(KeyName))
                            {
                                Exception.Data.Add(KeyName, parameter.ToString());
                            }
                        }
                    }
                }
            }

            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            public CallerInfo(int Level)
            {
                try
                {
                    System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
                    System.Reflection.MethodBase methodbase = stackTrace.GetFrame(Level + 1).GetMethod();
                    parameterinfos = methodbase.GetParameters();
                    assemblyname = methodbase.ReflectedType.Assembly.ManifestModule.Name;
                    identifiername = methodbase.ReflectedType.FullName + "." + methodbase.Name;
                }
                catch
                {
                    //broken
                }
            }
            void IDisposable.Dispose()
            {
                parameterinfos = null;
            }
        }
    }
}
0

1 Answer 1

1

Thank you very much for the good Minimal, Complete, and Verifiable code example. While the question as originally worded was not especially clear, having a good MCVE ensured that the exact issue can easily be understood. (It's unfortunate that three different people didn't bother to look at the most important part of the question…it seems the worst questions get up-voted, even while a not-entirely-clear question but which includes full code — the very most important part of any question — gets down-voted :( ).


Anyway, the issue here is your use of params in conjunction with the fact that the parameter itself is an array. It's important to understand what params actually means: the parameter declared in that way is in fact an array, and follows all the normal rules for regular array parameters. The only thing that params gives you is that you may optionally populate the array by providing multiple argument values, and the compiler will take those values and combine them into an array.

Where you got into trouble is that if you provide an array as the argument value, the compiler treats that as the actual array argument that was declared for the method and does not do any additional work.

The issue might have been more obvious if you'd been passing an object[] instead of a string[]. In that case, you can easily see that the whole object[] array matches exactly the parameter type for the LogException() method, and so is passed directly rather than being stored in another object[]. As it happens, arrays in C# are "covariant". In this case, the main thing that means is that if a method is expecting an object[] array, you can pass it an array of any type, because the elements of the passed array inherit the object type.

So when you pass the ArrayType value, the C# compiler recognizes this as compatible with the LogException() method's object[] parameter type, and just passes the array itself as that parameter, rather than storing it as a single element in an object[]. Then later when you go to retrieve the parameter values, it seems as though your LogException() method had been called by a method with two different parameters, i.e. two string values of "val1" and "val2", respectively.

So, how to fix this? Very easy: you just have to hide the array nature of the value from the C# compiler for the purpose of the call:

LogException(ex, (object)ArrayType);

I.e. in your TestMethod1() method, cast the ArrayType value to object when calling LogException(). This will force the compiler to treat the array object as a simple object value, preventing it from matching the value's type to the params object[] args parameter type, and store the value in a new object[] array for the call as you'd expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.