title: How to convert variable name to string in c#.net?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp">Finding the Variable Name passed to a Function in C#</a>  </p>
  </blockquote>
  
  
  
  <pre><code>public new Dictionary&lt;string, string&gt; Attributes { get; set; }
  public string StringAttributes = string.Empty;
  
  public int? MaxLength { get; set; }
  public int? Size { get; set; }
  public int? Width { get; set; }
  public int? Height { get; set; }
  
  protected override void OnInit(EventArgs e) {
      Attributes = new Dictionary&lt;string, string&gt;();
      Attributes.Add("MaxLength", MaxLength.ToString());
      Attributes.Add("Size", Size.ToString());
      Attributes.Add("Width", Width.ToString());
      Attributes.Add("Height", Height.ToString());
      base.OnInit(e);
  }
  
  protected override void OnPreRender(EventArgs e) {
      if (Attributes != null) {
          StringBuilder attributes = new StringBuilder();
          foreach (var item in Attributes) {
              if (!string.IsNullOrWhiteSpace(item.Value)) {
                  attributes.Append(item.Key + "=\"" + item.Value + "\" ");
              }
          }
          StringAttributes = attributes.ToString();
      }
  }
  </code></pre>
  
  <p>The problem here is, instead of using <code>Attributes.Add("MaxLength", MaxLength.ToString());</code> and repeat the same process for other properties, could we not just make a function that is also able to add values to the dictionary, where the keys to be added are their variable names?
  Say, </p>
  
  <pre><code>public void addAttribute(object variable){
      Attributes = new Dictionary&lt;string, string&gt;();
      Attributes.Add(variable.Name, variable.Value);
  }...
  </code></pre>
  
  <p>I guess this is also possible to do with reflection, getting all the nullable properties and looping through them then adding each to the dictionary... But for as long as there are any other ways, we would not stick to reflection.</p>
  
  <p>But if reflection is the only choice, then another problem now would be how to get the nullable properties of the class... </p>
  
  <p>Any help would be greatly appreciated. Thank you.</p>