0

I have a class :

class Sample
{  
   ...
}

and define a property like this:

Sample sampleParam =new Sample(...);

and have a function :

private void Func(Sample s)
{}

and use it like:

Func(sampleParam);

can I get the 's' name in the function? I mean can I get "sampleParam"(the name of param)?

It sounds odd; but I need the name of the passed param.

and sorry for this type of asking; I just wanted to ask my question as simple as possible

Arsalan
  • 709
  • 2
  • 14
  • 27
  • 1
    I know that this won't answer your question but you should try to do whatever you do in a different way. Maybe if you share your objective we can help with that – Claudio Redi Jun 26 '15 at 15:34
  • 4
    That isn't a property. None of this is making any sense to me. – Aron Jun 26 '15 at 15:34
  • The line `Sample sampleParam =new Sample(...);` is create an object of type `Sample`. There is no property here. Was that a typo? – Broots Waymb Jun 26 '15 at 15:35
  • Take a look at [CallerMemberNameAttribute](https://msdn.microsoft.com/en-US/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx) – Binkan Salaryman Jun 26 '15 at 15:35
  • Take a look at the Type object. pretty sure you'll find what you need there : https://msdn.microsoft.com/en-us/library/system.type.aspx – poudigne Jun 26 '15 at 15:36
  • See http://stackoverflow.com/questions/9801624/get-name-of-a-variable-or-parameter and https://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.name(v=vs.110).aspx – WraithNath Jun 26 '15 at 15:36
  • @PLAudet The link is not relevant at all – Binkan Salaryman Jun 26 '15 at 15:37
  • @BinkanSalaryman why is that ? – poudigne Jun 26 '15 at 15:37
  • Also look here (http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp) and search for concept of "reflection" – Nicko Po Jun 26 '15 at 15:37
  • See http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp – Ed B Jun 26 '15 at 15:38
  • Add a name property to the Sample class? Alternatively this may help: http://stackoverflow.com/questions/2820660/get-name-of-property-as-a-string – Patrick Allwood Jun 26 '15 at 15:55
  • Do you need the name of the variable containing the value you are passing to the function? I'd be surprised if that was possible, since, during execution, the variable represents a value - and that value is passed to the method – Benj Jun 26 '15 at 15:59

5 Answers5

1

You should never reference variable or property names from called methods - it's bad manners and bad design (mostly the latter).

There is nameof operator in C# 6.0, but it wasn't designed for this.

You could use expression trees, which would slightly change your syntax. If sampleParam is not a property but a variable, you can't really access it, because compiler does not store any references to that name in generated dll file.

Ryszard Fiński
  • 452
  • 3
  • 7
1
public string GetParamName(System.Reflection.MethodInfo method,int index)
{
    string strParameterName = string.Empty;

    if (method != null && method.GetParameters().Length > index)
        strParameterName = method.GetParameters()[index].Name;

    return retVal;
}

Yes there is a way to achieve this through Reflection...

0

I think it is not possible to get the name for a variable which value is passed to a method. But there is the compiler service CallerMemberNameAttribute which copies the name of the caller method (here the get accessor of our property Name) to the calling method if not specified:

class Person {
    static void Main(string[] args) {
        Person bart = new Person();
        bart.Name = "Bart";
        Console.ReadKey();
    }

    private string _name;
    public string Name {
        get {
            return _name;
        } set {
            _name = value;
            PropertyChanged(); //no need to fill in `Name` here! :)
        }
    }

    //automatically copy caller's name to `propertyName`, at compile time
    private void PropertyChanged([CallerMemberName] string propertyName = "") {
        object propertyValue = this.GetType().GetProperty(propertyName).GetValue(this);
        Console.WriteLine("Property '" + propertyName + "' changed the value to '" + propertyValue + "'");
    }
}

Prints:

Property 'Name' changed the value to 'Bart'
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29
0

This isn't exactly what you're asking for, but is perhaps closer to what you want, but you could take a look at System.Environment.StackTrace.

RoadieRich
  • 6,330
  • 3
  • 35
  • 52
0

If you mean can you get the name 'sampleParam' from INSIDE func? The the answer is no. There is nameof() in C#6.0 but 'sampleParam' inside not in scope inside the func. The variable s (of type Sample) is crated and assigned a ref to sampleParam.

You can get the name "s" inside Func. You can get the name "sampleParam" in the calling class (outside Func).

Example (available on dotnetfiddle)

using System;

public class Program
{
    public static Sample sampleParam {get; set;} =new Sample();
    public static void Main()
    {

        Console.WriteLine($"Name of property: {nameof(sampleParam)}");
        Func(sampleParam);
    }

    private static void Func(Sample s)
    {
        Console.Write($"Name of parameter: {nameof(s)}");
    }

}

public class Sample
{

}

Output:

Name of property: sampleParam
Name of parameter: s

Now this is a rather simplistic example. Func exists in the same class as sampleParam and there is only one property so one could derive the name but my assumption is despite your question stating it this way you are looking for a more generalized solution. The problem is that inside func the calling parameter name is not in scope. You could capture it via nameof in the calling method and pass it into func but you shouldn't that would be horrible code for a variety of reasons.

As described what you are doing is intentionally building fragile tightly coupled code which is something developers work very hard to prevent. The caller is not going to know the name of the parameter passed into func is important and shouldn't. This leads me to believe this an xy problem.

Community
  • 1
  • 1
Gerald Davis
  • 4,541
  • 2
  • 31
  • 47