How do I get the name of an application in C #?

In the customization of a visual C # application, we can create a series of customizations with a specific name, type, scope and value. I have access to the value by code:

string color= Myproject.Properties.Settings.Default.mycolor;

      

How can I get "mycolor", which is the name of this setting, in the output?

+3


source to share


3 answers


If you want the name of the parameter, then you want to get the name of the property. In his book Metaprogramming in .NET, Kevin Hazzard has a routine that looks something like this:

/// <summary>
/// Gets a property name string from a lambda expression to avoid the need
/// to hard-code the property name in tests.
/// </summary>
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

      

To call it, you would do the following:

string propertyName = GetPropertyName(() => Myproject.Properties.Settings.Default.mycolor);

      

I've added a static reflection utility to some of my projects to allow access to this and other tools.



EDIT

With July 20, 2015 set as the RTM date for Visual Studio 2015 and .NET 4.6, this looks like a good time to upgrade.

Luckily, all of my above code goes to C # 6 (.NET 4.6), as there is a new expression name that handles this very easily now:

string propertyName = nameof(Myproject.Properties.Settings.Default.mycolor);

      

Some of the new features are documented on the MSDN blog .

+3


source


A little extension method will help you:

public static string GetSettingName<TObject, TProperty>(this TObject settings, 
    Expression<Func<TObject, TProperty>> member) 
    where TObject : System.Configuration.ApplicationSettingsBase
{
    var expression = (MemberExpression)member.Body;
    return expression.Member.Name;
}

      



And this usage:

var settingName = Properties.Settings.Default.GetSettingName(s => s.mycolor);

      

+2


source


Here is my understanding of your requirement:

  • You need to know the parameter name from the object
  • fe you want to get "mycolor"

    from a color like "Red"

    (let's assume this is the default)

You can use a collection Properties

and Enumerable.FirstOrDefault

:

var colorProperty = Settings.Default.Properties.Cast<System.Configuration.SettingsProperty>()
    .FirstOrDefault(p => color.Equals(p.DefaultValue)); // color f.e "Red"
string nameOfProperty = null;
if (colorProperty != null)
    nameOfProperty = colorProperty.Name;

      

+1


source







All Articles