Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get field by name

I am trying to create a function that can return a field from its object.

Here is what I have so far.

public class Base
{
    public string thing = "Thing";
    public T GetAttribute<T>(string _name)
    {
        return (T)typeof(T).GetProperty(_name).GetValue(this, null);
    }
}

What I would ideally like is to call:

string thingy = GetAttribute<string>("thing");

but I have a feeling I got the wrong end of the stick when reading up on this because I keep getting null reference exceptions.

like image 474
inadequateMonkey Avatar asked Dec 30 '15 14:12

inadequateMonkey


People also ask

How do you get a name field?

lang. reflect. Field used to get the name of the field represented by this Field object. When a class contains a field and we want to get the name of that field then we can use this method to return the name of Field.

How do you get a field name as a string?

To get field's name, go like that: //use the field object from the example above field. getName(); // it is in String.

What is field name in C#?

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type. A class or struct may have instance fields, static fields, or both. Instance fields are specific to an instance of a type.

What is getField in Java?

The getField() method of java Class class returns a field object which represents the public member field of the class or interface represented by this Class object. A string specifying the simple name of the desired field is passed as the parameter.


1 Answers

First thing - thing is a field, not a property.

Another thing is that you have to change parameter type to get it working:

public class Base {

   public string thing = "Thing";

   public T GetAttribute<T> ( string _name ) {
      return (T)typeof(Base).GetField( _name ).GetValue (this, null);
   }   
}

BTW - you can get property/field value by referencing an instance:

var instance = new Base();
var value = instance.thing;
like image 119
kamil-mrzyglod Avatar answered Oct 02 '22 18:10

kamil-mrzyglod