This question already has answers here:
How to get a property value based on the name
(8 answers)
Closed 2 years ago.
I want to get the value of a desired variable among several variables in a class
When i put string and class in Method, the method returns the value of the variable with the same name as the string received among all variables included in the class.
This method can get any type of class. So this method need to use generic.
Do anyone have a good idea for my problem?
public class A
{
public int valA_int;
public string valA_string;
public float valA_float;
public long valA_long;
}
public class B
{
public int valB_int;
public string valB_string;
public float valB_float;
public long valB_long;
}
public static class Method {
public static object GetvalueFromClass<T>(string varName, T classType) {
//Find val from class
return object;
}
}
public class Program {
public A aClass;
public B bClass;
public void MainProgram() {
object valA_int = Method.GetvalueFromClass("valA_int", aClass);
object valB_long = Method.GetvalueFromClass("valB_long", bClass);
}
}
The concept of method is like this.
please help me to figure out my problem.
your task already defined.
if you use
#{Class}.GetType().GetProperty(#{VariableName}).GetValue(#{DefinedClass}, null);
you can easily get variable from your class with variable name.
it returns variable as object. so you need to convert it
Example code
CLASS YourClass = [A CLASS WHICH IS PRE DEFINED];
object Target = YourClass.GetType().GetProperty("YOUR VARIABLE").GetValue(YourClass , null);
ok, use reflection to get all the variables in the object, then run through a loop checking them against the string of the property name. From there you should be able to return the value.
So something like
public object FindValByName(string PropName)
{
PropName = PropName.ToLower();
var props = this.GetType().GetProperties();
foreach(var item in props) {
if(item.Name.ToLower() == PropName) {
return item.GetValue(this);
}
}
}
Related
This question already has answers here:
Do properties always have a value when unset?
(4 answers)
Closed 4 years ago.
I found this code on a PDF tutorial:
public class Chien
{
public static int NombreDeChiens { get; set; }
private string prenom;
public Chien(string prenomDuChien)
{
prenom = prenomDuChien;
NombreDeChiens++;
}
public void Aboyer()
{
Console.WriteLine("Wouaf ! Je suis " + prenom);
}
}
There is no initialization in this code though in the constructor there is this incrementation. So how is it possible?
A property is nothing but a field wrapped with a get- and a set-method. As fields do have an initial value, properties also do.
E.g. the following code:
public int MyProperty { get; set; }
is translated to something like this by the compiler:
private int _myProperty; // the actual name of the field defers and is only known by the compiler
public int get_MyProperty() { return this._myProperty; }
public void set_MyProperty(int value) { this._myProperty = value; }
So the question boils down to "have fields a default-value"? The answer to this question is yes, they do: null for reference-types and the default-value for all structs, e.g. 0 for int, or 0f for float.
This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 4 years ago.
I have been working with my software using C# in visual studio. But i want to return multiple values in my method, How to return multiple values in a method in C#.... Is it possible??
You can use .NET 4.0+'s Tuple:
For example:
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
it's much easier now
For example:
public (int, int) GetMultipleValue()
{
return (1,2);
}
Do you want to return values of a single type? In that case you can return an array of values. If you want to return different type of values you can create an object, struct or a tuple with specified parameters and then assign those values to these parameters. After you create an object you can return it from a method.
Example with an object:
public class DataContainer
{
public string stringType { get; set; }
public int intType { get; set; }
public bool boolType {get; set}
public DataContainer(string string_type, int int__type, bool bool_type)
{
stringType = string_type;
intType = int__type;
boolType = bool_type;
}
}
Example with a struct:
public struct DataContainer
{
public stringstringType;
public int intType;
public bool boolType;
}
Example with a tuple:
var DataContainer= new Tuple<string, int, bool>(stringValue, intValue, boolValue);
You could create a struct that has multiple variables inside of it.
See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct .
Your options are returning a struct, a class, a (named?) tuple or alternatively you can use out parameters
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to set object property through Reflection
If I have the following program:
public class MyClass
{
public int MyIntProp {
get;
set;
}
public string MyStringProp {
get;
set;
}
}
public class MyMainClass
{
private const string PropertyName = "MyIntProp";
private MyClass _myClass;
public MyMainClass()
{
_myClass = new MyClass();
// _myClass.PropertyName = 5;
}
}
What I want to do is be able to assign a value of 5 to the MyIntProp property. Is it possible to do this using a string name? I though I saw something like this done before using LINQ, but I can't seem to remember the syntax or where I found it.
You can use Reflection with GetProperty method:
typeof(MyClass).GetProperty(PropertyName).SetValue(_myClass, 5);
Can some one explain to me why the GetProperties method would not return public values if the class is setup as follows.
public class DocumentA
{
public string AgencyNumber = string.Empty;
public bool Description;
public bool Establishment;
}
I am trying to setup a simple unit test method to play around with
The method is as follows and it has all the appropriate using statements and references.
All I'm doing is calling the following but it returns 0
PropertyInfo[] pi = target.GetProperties(BindingFlags.Public | BindingFlags.Instance);
But if I setup the class with private members and public properties it works fine.
The reason I didn't setup up the the class the old school way was because it has 61 properties and doing that would increase my lines of code to at least triple that. I would be a maintenance nightmare.
You haven't declared any properties - you've declared fields. Here's similar code with properties:
public class DocumentA
{
public string AgencyNumber { get; set; }
public bool Description { get; set; }
public bool Establishment { get; set; }
public DocumentA()
{
AgencyNumber = "";
}
}
I would strongly advise you to use properties as above (or possibly with more restricted setters) instead of just changing to use Type.GetFields. Public fields violate encapsulation. (Public mutable properties aren't great on the encapsulation front, but at least they give an API, the implementation of which can be changed later.)
Because the way you have declared your class now is using Fields. If you want to access the fields trough reflection you should use Type.GetFields() (see Types.GetFields Method1)
I don't now which version of C# you're using but the property syntax has changed in C# 2 to the following:
public class Foo
{
public string MyField;
public string MyProperty {get;set;}
}
Wouldn't this help in reducing the amount of code?
I see this thread is already four years old, but none the less I was unsatisfied with the answers provided. OP should note that OP is referring to Fields not Properties. To dynamically reset all fields (expansion proof) try:
/**
* method to iterate through Vehicle class fields (dynamic..)
* resets each field to null
**/
public void reset(){
try{
Type myType = this.GetType(); //get the type handle of a specified class
FieldInfo[] myfield = myType.GetFields(); //get the fields of the specified class
for (int pointer = 0; pointer < myfield.Length ; pointer++){
myfield[pointer].SetValue(this, null); //takes field from this instance and fills it with null
}
}
catch(Exception e){
Debug.Log (e.Message); //prints error message to terminal
}
}
Note that GetFields() only has access to public fields for obvious reasons.
As mentioned, these are fields not properties. The property syntax would be:
public class DocumentA {
public string AgencyNumber { get; set; }
public bool Description { get; set; }
public bool Establishment { get; set;}
}
In C# if I have this in a class:
public int SomeNumber
{
get { return 6; }
}
How can I read (get) that number from a function in the same class if the function receives a variable with the same name? Example:
public bool SomeFunction(int SomeNumber)
{
check if SomeNumber (the one passed to this function) == SomeNumber (the one from the public int)
}
You would simply invoke the property get in the method:
public void MyMethod()
{
var someNum = SomeNumber; // basically, var somNum = this.SomeNumber;
}
EDIT: To clarify with OP's edit:
public void MyMethod(int someNumber)
// Change the naming of your parameter so it doesnt clash with the property
{
if(someNumber == SomeNumber)
// Do Stuff
}
Same as if it were a field:
public void SomeOtherFunction()
{
var x = SomeNumber;
}
Although the other suggestions do work well (and adhere to easier to read/maintain code), they don't directly answer your question. Given a class
public class SomeClass
{
public int SomeNumber { get { return 6; } }
...
And a function with a parameter passed in
public void SomeMethod(int SomeNumber)
{
// Your code here...
You can access the passed in parameter and property like so:
if (SomeNumber > this.SomeNumber)
{
// Your results here
The distinction is that if you refer to just the variable name, it will use the variable from the same scope, i.e. the passed in variable. If you specify use "this." then you always get the class member.
Note: This does not work with Static classes, as there is no instance of the class. (Can't use "this.whatever") and you will be stuck. There are many coding Standards out there and some of them states that it is best practice to use the form "myVariable" for method parameters, "MyVariable" for property names, and _myVariable for property backing stores, to easily distinguish between them in your code.
public class FavoriteNumber
{
public int SomeNumber
{
get { return 6; }
}
Public int Twelve()
{
return SomeNumber*2;
}
}
Please run this code and you will get it.. Use this operator to refer the class level variale.
public void CheckNumber(int SomeNumber)
{
Console.WriteLine(SomeNumber);
Console.WriteLine(this.SomeNumber);
}