Click here to Skip to main content
15,880,392 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi All,

How can I change value of a variable of a method when it is invoked using Reflection.

At present below code is updating value of local variable (class level).

Why? : I am writing one Unit Test Case where object of a class might get changed its internal behavior and to test that negative scenario in Unit Test, I want to change value of that variable at runtime like setting an object to Null which sometime returning as null from Database and failing our application.

C#
private void SetVariableValue(BehaviorState behaviorState, string variableName,object value)
{
    Type t = typeof(BehaviorState);


    foreach (var member in t.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
    {
        if (member.Name == variableName)
        {
            // changing the variable
            FieldInfo fi = (FieldInfo)member;
            fi.SetValue(behaviorState, value);
            break;
        }

    }
}


Thanks
Rushi
Posted
Updated 17-Oct-13 8:06am
v3
Comments
Sergey Alexandrovich Kryukov 17-Oct-13 13:59pm    
Why?!
—SA
Joshi, Rushikesh 17-Oct-13 14:06pm    
Why? : I am writing one Unit Test Case where object of a class might get changed its internal behavior and to test that negative scenario in Unit Test, I want to change value of that variable at runtime like setting an object to Null which sometime returning as null from Database and failing our application.
Sergey Alexandrovich Kryukov 17-Oct-13 14:11pm    
You don't seem to understand what you are doing. Local variables are not just inaccessible by Reflection (in the sense I explained in my answer), in the context you show they simply don't even exist. Do you understand why?
—SA

1 solution

Reflection does not touch variables, it only deals with types, their members and attributes. (I don't mean System.Reflection.Emit, but this is unrelated to your question.)
Your purpose is totally unclear. The local variables are stack objects, they are fully accessible to your method in its stack frame; and outside that stack frame they simply don't exist. To get some idea, please read this: http://en.wikipedia.org/wiki/Call_stack[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900