Reflection not return value - c#

I am trying to access field value using reflection, but cant make it work
public class Menssagens
{
public string Teste2;
public void Falar(string key, string id)
{
string json = File.ReadAllText(#"bin/" + id + ".json");
Menssagens dotNet = JsonConvert.DeserializeObject<Menssagens>(json);
Console.WriteLine(dotNet.Teste2); //Works fine
Console.WriteLine(typeof(Menssagens).GetField(key).GetValue(this));
//Dont works, returns nothing
}

You're accessing the property value on this. You never set it on this, so it returns null.
You probably want to access the value on the instance you created.
In fact, your method should be static.

Related

Call Property based on a string of its name

I need to call a public property of a class based on the string value of its name, as I won't know until run time what properties are required. I'm trying to use reflections unsuccessfully. The class looks like this:
class FieldCalculation
{
public string MyValue
{
get
{
return "Test Data";
}
}
}
I think access the value of the property should look something like this:
FieldCalculation myClass = new FieldCalculation();
string value = myClass.GetType().GetProperty("MyValue");
Any help would be appreciated.
You nearly had it. What you were doing was getting the property definition. You need to ask that property to get you the value, and you pass it the instance. This is the working code:
FieldCalculation myClass = new FieldCalculation();
string value = (string)myClass.GetType().GetProperty("MyValue").GetValue(myClass);

Parsing within a Set method

I know this might be a simple question but I was wondering in C# what is the best way to parse an incoming string within a set method to an int e.g. if I have
public int foo {get; set;}
On the set I want to parse a incoming string
There are a lot of ways to skin this cat. This is how I would do it.
Let's say your property is:
public int Foo
{
get { return _foo; }
set { _foo = value; }
}
You could do is add a helper method on your class:
public void SetFoo(string sFoo)
{
Foo = Convert.ToInt32(sFoo);
}
Then, when you need to set the value using a string, you can call that method:
myFooObject.SetFoo("4");
I guess you have some string and you want to parse it into int by setter. Of course, you can do it, but the property must be string.
private int foo
public string Foo
{
get
{
return foo.ToString();
}
set
{
foo = Int32.Parse(value);
}
}
But remember that Int32.Parse() throws an exception if your string is not a number. You should consider using Int32.TryParse() which could be a better choice in this case.
Do you mean this?
private int _foo;
public int Foo
{
get { return _foo; }
set
{
_foo = value;
ParseFoo(_foo);
}
}
but since you're talking about strings...
private string _foo;
public string Foo
{
get { return _foo; }
set {
_foo = value;
ParseIncomingString(_foo);
}
}
Well since the property is of type int, it's not possible to assign a string to it. So you need to do this parsing before assigning the value to your property.
Alternatively you could make your setter private, and have a public method that takes string, and do your validation inside of the method set the property if validation succeeds.
I would recommend you to make sure that your value is an int before you set it to your property when the set method is called automatically. This means that the string you want to set to your property should be parsed before it's set.
If you want to do it as you asked then you could simply use the Int32.Parse(value) or Int32.TryParse(value).
The difference between those two is that Parse(value) method throws an exception if the the parsing fails which means that you have to use try-catch block if you want to catch the exception and where TryParse(value) returns false if the parsing fails and true on success.
You can read more at: https://msdn.microsoft.com/en-us/library/bb397679.aspx

How to return value of the method from a different class to the output label

I have a method created in class1 called method1.
Im trying to display method1 in a label object. Hopefully I described this properly. Any help would be appreciated. Thanks in advance.
Here is my class Ticket User.
//property accessors
public string CreateAccountMessage
{ get{
return "Congratulations" + firstName + "Your account has been created. Your username is" + username;
} set
{ CreateAccountMessage = value;
}
}
//CreateAccount method
public string CreateAccount()
{ return CreateAccountMessage;
}}}
This is where i need to return CreateAccountMessage
protected void btnCreateAccount_Click(object sender, EventArgs e)
{
lblsomelabel.Text = TicketUser. (this is where it only shows Equals and ReferenceEquals
}
ok there are a few issues - on the property set for CreateAccountMessage, CreateAccountMessage = value is setting the property, you almost certainly want a private variable and a full property here...read here for more info on properties
Though I think your real issue is that you are trying to access a static functions of the class TicketUser - when it should be a normal instance method call -
e.g. you should be able to do the following in code:
TicketUser user = new TicketUser ();
user. (and then intellisense will kick in)
The fact you have no intellisense is because you are accessing the class directly (and its static methods, which don't match) - you probably need to re-think your architecture - maybe passing the instance in as a field of a custom event arg

Auto-implemented properties and additional function

Is there a way to do something like this in C#:
public class Class2 {
public string PropertyName1 { get
{
return this; //i mean "PropertyName1"
}
set {
this = value;
DoAdditionalFunction();
}
}
Because I need to call additional function in the "set" I need to have an extra private field like
private string _propertyName1;
public string PropertyName1 { get
{
return _propertyName1;
}
set {
_propertyName1= value;
DoAdditionalFunction();
}
I don't want to use additional property like _propertyName1. Is there a way to accomplish this or any best practices?
No - if you need any behaviour other than the most trivial "set a field, return the field value", you need to write "full" properties. Automatically implemented properties are only a shorthand for trivial properties.
Note that you haven't really got an "extra" private field, in terms of the actual contents of an object - it's just that you're explicitly declaring the private field instead of letting the compiler do it for you as part of the automatically implemented property.
(It's not clear what your first property is trying to do - setting this in a class is invalid, and you can't return this from a property of type string unless you've got a conversion to string...)

How to pass value back to original caller c#

I have a class that adds information to a list and then does some calculations. Now I want to return that to the original program. How do I do that?
In Main program I have public value
public string ResponseTime
{
get { return _ResponseTime; }
set { _ResponseTime = value; }
}
MAIN FUNCTION()
Within the main function I call the class which calculates the correct response time and returns it back. The question is how do I capture it in this main program?
ListTest.CalculateResponseTime(_ResponseTime); - need to use the value that returns and set ResponseTime to that value.
public static string CalculateResponseTime(string responseTime)
{
}
Are you just asking how to get the return value from a function??
ResponseTime = ListTest.CalculateResponseTime(_ResponseTime);
pass the parameter by reference
public void CalculateResponseTime(ref string responseTime)
{
// your code
}
you don't need to return the string, becuase when your modify the value of your string in the function ,the value will be modified the the original location (memory address) and not only in the scope of your function.
In this way you can assign directly the property of your class as function parameter, and when the function ends your property has the value modified too.
The alternative is passing your parameter as value and return the reult as assign of your property.
if you need more information about it. MSDN is your friend
ResponseTime = [insert calculated value]
(...at least, that's how I'm interpreting your question...)

Categories