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...)
Related
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.
Assuming I will need to access the values contained within a given file a small number of times, from different methods, can I include some sort of boolean value within a method to determine whether or not it is appropriate to call the file?
Lets say I have the file config.cfg. In that file, there are three values:
string/name>max|
bool/adult>yes|
int/age>20|
The method getUserName() returns the value of "max". It does this by calling the file:
using (StreamReader reader = new StreamReader(path))
{
//get line beginning with string/name here
return //string value containing name
}
Let's assume I need to use the value of name several times, as well as the values isAdult and clientAge. Rather than accessing the file over and over again, it could be much easier to save the requested value in some form of static variable. However, this variable still needs to be changed in value at least once, when the method is first called.
Can I do this inside the method getUserName()?
Furthermore, is this idea even possible within the bounds of OOP? Is it a similar concept to Prefetch?
It really looks to me that you need to access a field in a lazy way (i.e. only if needed, when needed). If so .NET has Lazy class for such cases which also provides thread safety out of the box:
public static Lazy<string> Name { get; } = new Lazy<string>(() => ReadNameFromFile());
Lazy will also ensure that you only create value once (i.e. call initiailization method) and on later calls it will simply return already retrieved value.
Create a static class. Something like this:
public static class ClientConfig{
public static string Name{get;set;}
public static bool IsAdult{get;set;}
public static int Age{get;set;}
public static void Load(){
// load your values
// ClientConfig.Name = name from file etc.
}
public static void Save(string newName, int age, bool value){
// save your values to the config file
}
}
And call ClientConfig.Load() first time when your app starts, for example (or whenever you need to retrieve config data)
I have a very basic understanding of using this technique so I probably and missing something simple. All I want to do is add a variable that holds the TOTAL items but the variable seems to be getting initialized back to 0 when I check it. My best guess is something is going out of scope and I am losing the value.
I call a function that passes a delegate(?)
[TestMethod]
public void Batch_Update_Is_Working()
{
DataTable dt = ExcelHelper.ReadAsDataTable(pathFileName);
EncompassBoxHelper.UpdateBoxes(ec, dt, progess => UpdateProgressBar(pi));
}
Inside the function I want to pass a value back.
public static void UpdateBoxes(EncompassConnection ec, DataTable dt, Action<ProgressInfo> updateProgress)
{
Session s = EncompassSession.Instance(ec.Url, ec.Name, ec.Password);
updateProgress(new ProgressInfo(dt.Rows.Count));
This is where the value is stored. In ItemsTotal. All good so far.
public class ProgressInfo
{
public int itemsProcessed { get; set; }
public int itemsTotal { get; set; }
public ProgressInfo()
{
}
public ProgressInfo(int it)
{
itemsTotal = it;
}
}
Now when it goes to the callback the value is 0??? pi.itemsProcessed is suppose to be 100.
public void UpdateProgressBar(ProgressInfo pi)
{
pi.itemsProcessed++;
Debug.WriteLine("Progress Info.ItemsProcessed: " + pi.itemsProcessed);
Debug.WriteLine("Progress Info.ItemsTotal: " + pi.itemsTotal);
}
Change your
EncompassBoxHelper.UpdateBoxes(ec, dt, progess => UpdateProgressBar(pi));
to
EncompassBoxHelper.UpdateBoxes(ec, dt, UpdateProgressBar);
Instead of sending the UpdateProgressBar() method to match the delegate expected in UpdateBoxes parameter, you're creating a new one by converting lambda expression, telling it to call itself specifically with a parameter of pi, instead of the one, that should be passed inside UpdateBoxes method (the new ProgressInfo(dt.Rows.Count) object).
Looks like your pi variable is not being passed by reference so it is never really getting updated. Honestly changing a value like pi.itemsProcessed++ in your delegate function is not very common although there are ways to do it like this.
Once your delegate supports passing in a variable with the "ref" keyword, then you should be able to call your delegate with something like this:
progess => UpdateProgressBar(ref pi)
You could also make pi a static variable and then it can be updated from your delegate as well so you don't have to worry about passing it around.
Do I need to declare a class-level variable to hold a property, or can I just refer to self.{propertyname} in the getter/setter?
In other words, can I do this? (where I haven't defined mongoFormId anywhere):
public string mongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way).
private string _mongoFormId;
public string mongoFormId
{
get { return this._mongoFormId; }
set
{
this._mongoFormId = value;
revalidateTransformation();
}
}
UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field.
You need to set a field variable and store the value there, if you're going to use custom getter and setter.
With the code you have right now you will be running into a stack overflow exception. When you assign something to mongoFormId, you'll execute the line this.MongoFormId = value;. This is an assignment to mongoFormId, resulting in executing the line this.MongoFormId = value;, and so on. It won't ever stop.
The correct way is a field:
private string _mongoFormId;
public string mongoFormId {
get { return this._mongoFormId; }
set {
this._mongoFormId = value;
revalidateTransformation();
}
}
You should have a backing variable. Take a closer look:
get { return this.mongoFormId; }
Is going to call the getter on mongoFormId, which will call that code again, and again, and again! Defining a backing variable will avoid the infinite recursive call.
Check MSDN Properties Overview
While a property definition generally includes a private data member,
this is not required. The get accessor could return a value without
accessing a private data member. One example is a property whose get
method returns the system time. Properties enable data hiding, the
accessor methods hide the implementation of the property.
You can do it both the ways.
If you want to have a class level member variable then do it this way -
public class sampleClass
{
private string _mongoFormId;
public string mongoFormId {
get { return _mongoFormId; }
set {
_mongoFormId = value;
revalidateTransformation();
}
}
}
Or do this simple in class, if no need for revalidateTransformation() execution call there
public class sampleClass
{
public string mongoFormId {get; set;}
}
This won't work since you get a recursive call to the property.
If I'm not mistaken, the result will be a StackOverflowException.
You must use a variable.
private string mongoFormId;
public string MongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
If you don't have to execute revalidateTransformation, you can use the auto-property.
This will create a backingfiled for you behind the scene.
public string MongoFormId { get; set; }
With the code you wrote, you are creating a recursive endless loop on both the get and set. The this keyword refer to the current class, not the property you are in.
So yes, you need to declare a private field. And to avoid confusion, create properties following the MSDN Naming Guideline (Use Pascal case for properties, camel case for private fields). And please do the same for your methods, it should be RevalidateTransformation instead of revalidateTransformation if you follow the C# convention instead of java's.
private string mongoFormId;
public string MongoFormId
{
get
{
return mongoFormId;
}
set
{
mongoFormId = value;
RevalidateTransformation();
}
}
public string mongoFormId {
get {
return this.mongoFormId;
}
set {
this.mongoFormId = value;
revalidateTransformation();
}
}
this way you have the Function recursive on all paths
The only way i see is to use a private data member. As other boys tells.
I often have a situation like this when creating simple data objects. I have a property called Label that should have a default based on the Name of the object. So if no label is set then the Name is used otherwise use the set Label. A simple example in C#
public class FooBat {
public string Name { get; set; }
public string Label {
get {
if (_label == null) return Name;
return _label;
}
set { _label = value; }
}
}
Now the problem is if you want to edit this object you can't just bind to the Label property or you will get the default value and it will look as if there is a value there when there really isn't. So what I end up doing is create another, read-only property that does the defaulting and I use that is all instances except for when the base object is being edited. This leads to many extra properties with weird names like LabelWithDefault. Another alternative I've tried is to make Label handle the defaulting and make a new property called RealLabel that is used for editing the base object. This is just as bad.
I've thought of moving the defaulting code somewhere else but I haven't found a good place for it in any "normal" model that does not replicate the defaulting code many times.
What I have started to do now is initialize the Label field when the Name field is set (and the Label field is not) and then treat the Label field as a normal field. This works but now the code for defaulting is tied to the wrong property. Why should the Name know that the Label field cares about it? So this is also not "right."
Does anyone have any better ways of handling this problem?
I think there is a little confusion about what I'm asking for. Basically I need two different views to the same object for two different uses. In the first is the editing of the object itself where I want unset fields to show as empty (unset). The second is for all other cases (including when the object is the value of a field of another object) where I want to show each field with its dynamically determined default. Just setting the default the first time doesn't no help because if the (in this case) Name field changes then the Label field must also change until the Label field is set.
The answers are getting closer but I still think that they are too targeted to the example I gave. I was trying to give a concrete example for expository purposes but in reality this is more of a best-practices issue. The example I gave was C# and for a string property but I have the same problem with most languages and systems that I use that have frameworks where the data access and data display are handled for you as well as for data types other than strings. Changing the object that is queried from the data source is possible but often tricky and knowing when to make the change (use a sublclass in this case but not in that one) is particularly difficult.
public class FooBat {
public string Name { get; set; }
public string Label {
get {
if (_label == null)
_label = Name;
return _label;
}
set { _label = value; }
}
}
Regarding your update:
You could subclass your object. The base-class would return null if the field has not been set and the sub-class would return your default value. Thus if you need to query if a value has been set, you would cast to the base-class.
Deleted previous answers/updates for brevity.
Update 2:
I would have to say the best way is to track whether the property has been set or not with an IsPropertySet bool. The Getter for the property would check that value to see if it should be returning its own value or the default value. And the setter for the property would set the IsPropertySet according to the set value (true if the value is not null, false if it is). The code that is using the class could then look at the IsPropertySet value to determine if it is receiving a set value or the default when it calls the Property's Getter.
public class FooBat {
public string Name { get; set; }
public bool IsLabelSet { get; set; }
public string Label {
get {
if (IsLabelSet)
return _label;
else
return Name;
}
set {
IsLabelSet = value != null;
_label = value;
}
}
}
I use a Nameable interface a lot (with getName()). Before I start, I'll suggest that you don't want to do this at all. It should be the domain of your display logic, not your domain objects. Usually it's the code consuming the FooBat that is able to make this decision in a better way than the object itself. That aside...
public interface Label{
string getLabel();
boolean isDefault(); //or isValued() or use instanceof expressions
}
public interface Nameable{
string getName();
}
public class FooBat implements Nameable {
public string Name { get; set; }
public Label Label {
get {
if (_label == null) {
_label = new DefaultLabel(this);
}
return _label;
}
set { _label = value; }
}
}
public class DefaultLabel implements Label{
public DefaultCharSequence(Nameable named){
this.named = named;
}
public string getLabel(){
return named.getName();
}
public boolean isDefault(){ return true; }
}
public class StringLabel implements Label {
...
}
It all essentially boils down to returning a better class for your label object.