im not sure why this isnt working, Im just passing a blank string and a number and it should check if that number is in the string, if not then it should add it into the string.the variable 'thing' gets set but the global variable that it is supposed to update(strduplicates) is never updated.
I call the function like this
Trackstats(strduplicates,"1337");
private void TrackStats(string thing, string variable)
{
if (!(thing.Contains(variable)))
{
thing += variable + ",";
}
}
A better design might be to return the new value:
private string TrackStats(string thing, string variable)
{
if (!(thing.Contains(variable)))
{
thing += variable + ",";
}
return thing;
}
and call it using:
strduplicates = this.TrackStats(strduplicates, "1337");
You are passing thing by value. You need to pass it by reference to make changes visible outside the method:
private void TrackStats(ref string thing, string variable)
{
if (!(thing.Contains(variable)))
{
thing += variable + ",";
}
}
Strings in .NET are immutable. Every modification will allocate and return a new instance.
To alter your global variable, you have to pass it as ref parameter, like this:
private void TrackStats(ref string thing, string variable)
{
if (!(thing.Contains(variable)))
{
thing += variable + ",";
}
}
Then you can call it like this:
TrackStats(ref strduplicates, "42");
string thing is not an output param. Use 'out string thing' to signal for output.
Related
I'm new to C#, having written a little in a CMS, but my background is mostly JavaScript related. That said, I am working in the "Scripting" client in OpenText Capture Center. When executing the code below I get the error "The Name 'srfOnly' does not exist in the current context"
If I move the variable declarations to within the function, I get the same error, If I move them to them to global I get the same error but on a different line number.
How can I access the variables srfOnly and otherDocs throughout the code?
//Parameters:
//DataPool data
//ITrace trace
// Checking if condition is fulfilled.
if (checkDocuments(data))
{
// Getting batch field named 'cc_SkipValidation'.
// Setting new value.
DOKuStar.Data.Xml.Bool skipValidationField = data.RootNode.Fields["cc_SkipValidation"] as DOKuStar.Data.Xml.Bool;
bool srfOnly = false;
bool otherDocs = false;
if(otherDocs == true)
{
skipValidationField.SetValue(false);
}
if(srfOnly == true && otherDocs == false)
{
skipValidationField.SetValue(true);
skipValidationField.State = DataState.Ok;
}
}
// !!! Closing bracket is neccessary !!!
}
// ------------------ Functions
public bool checkDocuments(DataPool dataPool)
{
foreach (Document doc in dataPool.RootNode.Documents)
{
if (doc.Name == "ServiceRequestForm")
{
srfOnly = true;
}
else if (doc.Name != "ServiceRequestForm")
{
otherDocs = true;
}
}
trace.WriteInfo("Trace info for Validation of srfOnly = " + srfOnly);
trace.WriteInfo("Trace info for Validation of otherDocs = " + otherDocs);
// !!! No closing bracket needed !!!
Variables are limited in scope by where they exist in your code. If you declare a variable within an if{} block, the variable only exists inside that block. If you declare a variable inside of a class but not within a class method, the variable is accessible to every method in the class. If you want a variable to be accessible to every class with in a project, you would normally declare it in a public static class.
For example...
public static class GlobalClass
{
public static string myGlobal="";
}
class myClass
{
string myClassVariable = "";
private void method()
{
//myGlobal is accessible using this
GlobalClass.myGlobal ="some value";
//myClassVariable is accessible here
myClassVariable = "somevalue";
if(condition)
{
//myClassVariable is also accessible here
myClassVariable = "somevalue";
string ifBlockVariable = "";
}
//ifBlockVariable is not accessible here
}
}
A variable is only accessible within the current block (and the blocks within that block). If you want to access the srfOnly variable within the checkDocuments method you can pass it as a parameter:
public bool checkDocuments(DataPool dataPool, bool srfOnly)
If you want the variable to be accessible from anywhere in the class, you can declare it as a a property of the class or an instance variable as following:
private bool _srfOnly;
I have this project:
And I need to use a variable that is in the "TransactionHandler.cs" in the "Enviar Faturas.cs" the TransactioHandler is a class library and the Enviar Faturas is a Windows Form.
Is it possible to do what I want? If so how should I do it?
UPDATE:
I have this variable declares in TransactionHandler.cs
var numfatura = _transaction.TransDocument + _transaction.TransSerial + _transaction.TransDocNumber;
And I need to use it on the Windows Form "Enviar Faturas".
UPDATE 2:
I have this code to select from a datagridview and write a textfile:
FileInfo arquivo = new FileInfo(#"C:\Users\HP8200\Desktop\faturas\" + r.Index + ".txt");
And I want to change the "r.index" for the variable I showed on the first update
I would suggest to use a property instead of a public field:
public class TransactionHandler
{
private static string numfatura = _transaction.TransDocument + _transaction.TransSerial + _transaction.TransDocNumber;
public static string Numfatura
{
get { return numfatura ; }
set { numfatura = value; }
}
}
From another class, you call your variable like this:
public class EnviarFaturas
{
public void DoSomething()
{
string r.Index= TransactionHandler.Numfatura;
}
}
Ok, from what I understand and having no idea of the execution flow you probably need something like this in the TransactionHandler (a property)
public int Numfatura
{
get
{
return this._transaction.TransDocument + this._transaction.TransSerial + this._transaction.TransDocNumber;
}
}
you can change the type to the one that stands behing the "var" in your code example.
To access it in the form you need an instance of the class (again I dont know what your logic is) but once you get it e.g.
var transactionHandler = new TransactionHandler();
you can simply try
r.Index = transactionHandler.Numfactura;
Keep in mind that you can hit the default data value (for int is 0) if your methods depend upon other event to happen.
I strongly suggest you to learn more about C# and Object Oriented Programming as Alexey Zimarev stated in the comments.
Also you should consider how to get/inject a concrete instance in the view.
Another good and related read will be singleton pattern, mvp and dependency injection.
Hello I have a console application that successfully runs input through an array containing Bad Words and if there is a bad word then it will output some text then quits the application. Now I want to see what I can do With DetectBW() Including assigning it to a string Although DetectBW() is a void type and it returns nothing so assigning it to a string isn't possible if it's written like this
EX.
string Name = DetectBW();
Here's my code for further explanation
namespace CleanApp
{
class Application
{
This region contains bad words. I wrote it in otherwise it says a whole list of bad words which wouldn't be good for obvious reason.
//profanityArray()
This region contains numbers 0-318 Including 318
//ProNumArray()
This is the Main method
#region//Main() Put everything thats finished in here to output it to Console Apllication.
static void Main(string[] args)
{
string[] Sarray = profanityArray();
int[] Iarray = ProNum();
// infinite loop that writes "Ask A question." then accepts a line of text from user (DetectBW())
while (true)
{
Console.WriteLine("Ask A question.");
DetectBW();
}
}
#endregion
This is the DetectBW() method it takes PlayerInput()string Method (Console.Readline) and runs it through the profanityArray and detects if PlayerInput() contains any of the bad words in profanityArray.
#region // DetectBW()
static void DetectBW()
{
string PI = PlayerInput();
string[] PIA = profanityArray();
foreach(int i in ProNum())
{
if(PI.ToLower().Contains(PIA[i]))
{
if (PI.ToLower().Contains(" "+PIA[i]+" "))
{
Console.WriteLine(PI + " contains a bad word(s)!");
Console.WriteLine("If you can't be polite then get off!!");
Environment.Exit(0);
break;
}
if (PI.ToLower().Contains(PIA[i]+" ")|| PI.ToLower().Contains(" " + PIA[i]))
{
Console.WriteLine(PI + " contains a bad word(s)!");
Console.WriteLine("If you can't be polite then get off!!");
Environment.Exit(0);
break;
}
}
}
}
#endregion
This region is PlayerInput() it is the string method I was talking about.
#region// PlayerInput()
static string PlayerInput()
{
string S = Console.ReadLine();
return S;
}
#endregion
This is where I plan to to take the DetectBW() run it and take the same playerInput() used in DetectBW() and assign it to a string var for later use.
static void App()
{
Console.WriteLine("What is you name?");
// This is where i need Help!!
}
}
}
So this is my question:
1.
I know that I can't assign a void to a string variable but is there a way to take the same playerInput() used in DetectBW(), so I know that there isn't any bad words in it, and assign it to a name string variable.
I have a problem with calling a string from another method from the same script. I'm not sure if this is possible with C#
Sorry I'm new to C# but I used to do this in Objective-C so maybe its possible here?
So, the below code is the method I'm trying to use that string into.
This method checked if a message is passed in the game and execute the code.
void HandleMessage(string message, string metadata)
{
if (message == "UnlockName")
{
}
}
This is the method that contains the string needed (txt)
void OutputText( string txt ) {
//string firstName = lastLoadedLevel.contact.name.Split(new char[] { ' ' })[0];
//txt = txt.Replace("C:", firstName + ":");
txt = txt.Replace("D:", "D's name:");
txt = txt.Replace("[name]", PlayerPrefs.GetString("name"));
chat.AddText( txt, delegate {
options.gameObject.SetActive( true );
} );
}
Right now it contains (txt.Replace) which happens automaticlly throughout the text output.
I want to do the same in (void HandleMessage) to only do the replace code when the message "UnlockName" is passed.
The 2 commented lines here are what I need to use but I don't know how to use them in the first method.
Any help would be great :)
Thank you in advance.
Something like this maybe:
string HandleMessage(string message, string txt)
{
if (message == "UnlockName")
{
string firstName = lastLoadedLevel.contact.name.Split(new char[] { ' ' })[0];
return txt.Replace("C:", firstName + ":");
}
}
void OutputText(string txt, string message)
{
txt = HandleMessage(message, txt);
txt = txt.Replace("D:", "D's name:");
txt = txt.Replace("[name]", PlayerPrefs.GetString("name"));
chat.AddText(txt, delegate
{
options.gameObject.SetActive(true);
});
}
Might need some tweaking, I made some guesses on how you might be using things.
If nothing else, it should give you the concept of one way to pass strings in and back out of a method. You could also keep the void signature and pass in the string to be manipulated as a ref parameter.
I am trying to validate a text box.I have validated a couple of other text boxes and they work fine.This one has some error.
My code looks correct to me.Someone please point out my mistake and tell me why Visual Studio 2010 is prompting an error of invalid arguments and variable not in current context:
You need to define string errorMsg; in addTextBox_Validating function before you call ValidAddress.
You need to define the errorMsg variable before using it as an out parameter.
string errorMsg;
Read up on how to use out.
Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
You need to pass a string as second parameter to ValidAddress. Try and add
string errorMsg = null;
as first line of addTextBox_Validating()
You have not declared the errorMsg string.
private void addTextBox_Validating (object sender, CancelEventArgs e)
{
string errorMsg = "";
...etc
}
In ValidAddress, the errorMsg string is passed in to the function as a parameter, so this issue does not arise.
As far as I can see, errorMsg is not declared anywhere.
Try changing addTextBox_Validating by adding a declaration for it
e.g.
var errorMsg = string.Empty;
if (!ValidAddress(...
An out variable needs to be declared in the context that it is used.
hth
Alan.
Where is errorMsg defined? It looks like it's sent in as a parameter to ValidAddress, so addTextBox_Validating, being a different method entirely, doesn't have access to it, as errorMsg is scoped to only exist in ValidAddress. Long story short, you haven't initialised your variable.