0

So im new at C# and i need to know if what i want to do is possible and how heres what I have,

public static class Sempre
{    
    public static string Raca = "";
}

// Sempre.Raca - can use like this

Now What I want to do is set a variable like thing = "example", and after this call Sempre but with the variable something like, Sempre.thing, but because it's a variable it would actually be Sempre.example.

Example same use I want in php,

$example = mean;
$_SESSION['name'.$example];

would create $_SESSION [namemean];
infused
  • 24,000
  • 13
  • 68
  • 78

3 Answers3

0

You can setup your type with an indexer. http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx. To use the indexer, you are required to have an instance class rather than a static one. If you really need to, you can use the singleton pattern to get "static" behavior.

Here is an example of using an indexer:

public class Sempre
{
    private Dictionary<string, string> _values = new Dictionary<string, string>();

    public string this[string key]
    {
        get { return _values[key]; }
        set { _values[key] = value; }
    }
}

You can use it like this:

Sempre sempre = new Sempre();

sempre["example"] = "my value";

string thing = "example";

Console.WriteLine(sempre[thing]);
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
0

Generally speaking you can not do this with objects in C# since the code is precompiled prior to runtime.

If you are specifically looking for an implementation of http session state, like you have in the PHP code example then this could be done. Session State is exposed at System.Web.SessionState.HttpSessionState and can be accessed via concatenated strings like in your example like this.

String example = "mean";
Session["name" + example] = 'bar';
//Session["namemean"] is now set to value of 'bar'
Aossey
  • 850
  • 4
  • 13
0

If you're only looking to do string substitution, you can also do something like this:

public class StringConstants
{
    public static string YES = "yes";
    public static string NO = "no";
}

then elsewhere

public void printmessage(bool value)
{ 
    if (value)
    {
    Console.writeline (string.Format "I Say {0}", StringConstants.YES);
    }
    else
    {
     Console.writeline (string.Format "I Say {0}", StringConstants.NO);
    } 
}

Documentation on string.Format for insertions and compositions is here

theodox
  • 12,028
  • 3
  • 23
  • 36