Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, November 3, 2010 3:34 PM
Here is an example of the concept I am used to in Coldfusion using EVALUATE and DEEVALUATE. Trying to accomplish something dynamic code side using ASP.NET C# .NET 4.0 and VS2010. The example should explain what I am trying to do... should be simple, reflaction, dynamic, eval of some kind? I thought I was close with Boolean.TryParse() but no luck even though logically it accepts a string why not convert to references variable?
PLEASE ADVISE
bool test1 = true;
string dynboolname = "test" + 1;
if(dynboolname == true)
{
**...
**
}
All replies (15)
Thursday, November 4, 2010 10:50 AM ✅Answered
Please declare those variables globally for the class and you can use the value in all methods.
Scope of the Variables declared in the method are confined to the method itself and reflection can't find those variables. You should atleast declare them globally like this
public partial class WebForm4 : System.Web.UI.Page
{
//Global Variables
public string dynamicvarname = "";
public string MyVar1 = "";
public string MyVar2 = "";
public string MyVar3 = "";
protected void Page_Load(object sender, EventArgs e)
{
dynamicvarname = "MyVar" + "1";
MyVar1 = "TEST1";
MyVar2 = "TEST2";
MyVar3 = "TEST3";
string dynamicvalue = this.GetType().GetField(dynamicvarname,BindingFlags.Public|BindingFlags.Instance).GetValue(this).ToString();
}
}
If you really want to see the variable values in the current stack, check this link
http://stackoverflow.com/questions/1552478/c-how-to-dump-all-variables-current-values-during-runtime
Friday, November 5, 2010 4:24 AM ✅Answered
Using reflection is really not the very most legible code, and as far as I know it's kind of "expensive" in terms of performance.
Do you have considered using a simple dictionary?
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary["variable1"] = "Hello World!";
dictionary["variable2"] = "Lorem Ipsum";
string variableName1 = "variable" + 1;
string variableName2 = "variable" + 2;
if (dictionary[variableName1] == "Hello World!")
{
// this is true
}
if (dictionary[variableName2] == "Lorem Ipsum")
{
// this is true
}
Friday, November 5, 2010 9:55 AM ✅Answered
That is cool... it's like an array without having to know the index of everything and eliminates the need to loop through to find something. THANKS!!! That is just... awesome solution.
MORE INFO...
You want to use Dictionary in your C# program for constant lookup times and to associate keys with values. Look at some examples of using Dictionary with Keys and KeyValuePair, as well as with classes and methods. This document has tips and examples for using Dictionary with keys and values using the C# programming language.
Dictionary provides fast lookup of elements.
Used when you have many different elements.
Found in the System.Collections.Generic namespace.
Specify the types of its keys and values.
Adding keys
To get started, let's add four keys with values to a Dictionary instance. Afterwards, we look inside the Dictionary using Visual Studio's debugger. You will see that the Dictionary is composed of separate keys and values. Here's the Dictionary code and then its internal view.
~~~ Program that uses Dictionary Add method (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("cat", 2);
d.Add("dog", 1);
d.Add("llama", 0);
d.Add("iguana", -1);
}
}
Looking up valuesHere we see how you can check to see if a
given string is present in a Dictionary with string keys. We look at
more types of Dictionaries further on, but here is the ContainsKey
method.
class Program
{
static void Main()
{
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("apple", 1);
d.Add("windows", 5);
// See if Dictionary contains this string
if (d.ContainsKey("apple")) // True
{
int v = d["apple"];
Console.WriteLine(v);
}
// See if Dictionary contains this string
if (d.ContainsKey("acorn"))
{
Console.WriteLine(false); // Nope
}
}
}
Friday, November 5, 2010 2:49 PM ✅Answered
No this is the problem with Microsoft developers. They don't see this stuff.
I thought Dictionary/HashTable/Map etc (different names in different programming languages and with slightly different properties) was something rather basic, but that is maybe only for Microsoft developers...
Here is a link to C# documentation for Dictionary http://msdn.microsoft.com/en-us/library/xfhwa508(v=VS.90).aspx
Note that the following syntax for adding entries are equivalent
dictionary["variable1"] = "Hello World!"; // dictionary[key] = value
dictionary.Add("variable2", "Lorem Ipsum"); // dictionary.Add(key, value);
Thursday, November 4, 2010 3:19 AM
Hi
This is n't possible the way you are trying in ASP.NET. You can try the following:
bool b = true;
string a = b.ToString();
if (a.ToLower() == "true")
{
Response.Write("True");
}
else
{
Response.Write("False");
}
Thursday, November 4, 2010 8:47 AM
string dynboolname = "test" + 1;
You can use dynamic data type but base type should be same. ex: You cannot assign an integer to a string or add an integer to a boolean
dynamic number = "0";
number += 1;
if (number == 1)
{
}
That will fail because String cannot be compared to integer.
Thursday, November 4, 2010 9:25 AM
No this is the problem with Microsoft developers. They don't see this stuff.
What I want is to dyanmically create the name of a variable that is declared earlier and run logic agaist it. Is this called reflection? How can I do it in a simple example like a gave above?
So in my example everyone assumes im trying to add a string and a number... wtf? I am concat a name then I need to find a way to EVAL() that name.
string variable1 = "Hello World!";
string namevar = "variable1";
if (EVAL(namevar) != "")
{
...
}
Thursday, November 4, 2010 9:32 AM
Respectfully, I think you missed what I was trying to do, here is another example. If anyone has experiance with Coldfusion sililar to EVALUATE() DEVALUATE(). The problem with your example is I have varaible names with a prefix but distinct only by the number at the end e.g. var1, var2, var3 so I want to use those dynamically based on mabe a user selection. Many things you can do with this I just an newer to C# coming from CF, PHP and other dev langs.
**//simplified even more example
**
**string variable1 = "Hello World!"; //you have a defined variable already
**
**string namevar = "variable1"; //you set up a name reference
**
** **
**if (EVAL(namevar) == ""Hello World!") //somehow you EVAL the name refer5ence and actually reference the variable with that name dynamically
**
{
**... //this would make hard coded nested if statements go away in dynamic applications
**
}
Thursday, November 4, 2010 9:45 AM
The way you are trying to read the value by referencing the address of variable is using pointers.
similar to this
http://msdn.microsoft.com/en-us/library/zcbcf4ta(v=VS.100).aspx
Otherwise, you can use Reflection to read the value with field name
public class TestClass
{
public TestClass()
{
}
public string strValue = "Test Value";
}
You can read that string value using reflection as
using System.Reflection;
TestClass tc = new TestClass();
string str = tc.GetType().GetField("strValue",BindingFlags.Public|BindingFlags.Instance).GetValue(tc).ToString();
If you want to use pointers for boolean,
bool IsValid = true;
unsafe
{
bool* value = &IsValid;
value += 1;
}
Thursday, November 4, 2010 10:16 AM
Looking at pointers:
Can you dynamically define the name of the variable using string concat for example?
int number1;
int number2;
int number3;
int* p = &number?; //address-of operator &
Thursday, November 4, 2010 10:31 AM
I haven't seen anything like that for pointers and & operator takes only the variable instance and it can't interpret a string as variable.
Thursday, November 4, 2010 10:40 AM
OK back to reflection... Here is a simple example but I think I might have the syntax off a bit. Only examples I can find are using objects and getting values of public varibales within those objects. I don;t need that just need to access a variable within the same sub-routine.
string MyVar1 = "TEST1";
string MyVar2 = "TEST2";
string MyVar3 = "TEST3";
string dynamicvarname = "MyVar" + "1";
string dynamicvalue = this.GetType().GetField(dynamicvarname, BindingFlags.Public | BindingFlags.Instance).GetValue(this).ToString();
//dynamicvalue should equal "TEST1"
Thursday, November 4, 2010 11:41 AM
I found away to use the dynamicvarname dynamically while grabbing value from database setting a single value. This eliminated the need for the public variables although that was exactly what I was looking for and will come in handy in other dynamic (non-hardcoded) applications.
THANKS!!!
Thursday, November 4, 2010 6:57 PM
The examples you give don't seem to need anything fancy
string variable1 = "Hello";
string namevar = variable1;
if (namevar == "Hello")
{
//...
}
(You would do the same sort of thing with your first example)
Friday, November 5, 2010 5:32 PM
I see what you did there Thanks for the proper approach to my dynamic delima.