Okay so in short:
I declare a variable, say
string str = "Random";
then I try to perform any sort of operation whatsoever, say
str.ToLower();
And neither visual studio, nor intellisense recognise it at all.
VS gives me the name "str" does not exist in the current context. This happened right after I installed xamarin but I'm not sure if it's related.
Also this issue would not occur if I was inside a method, just when I'm directly inside a class.
This is my code:
public class Program {
public void randomMethod() {
string str2 = "Random";
str.ToUpper(); //this line shows no errors
}
string str = "Random";
str.ToLower(); //this line does show the error
}
str would be underlined red and the warning mentioned above would appear.
Does anybody know what's going on?
you even point the issue out yourself
you cannot do this
public class Program {
string str = "Random";
str.ToLower(); //this line does show the error
}
when would you expect that code to run?
You must put executable code inside a function. You point out that this works.
I cannot propose a fix since I do not know what you are trying to do.
It is a scope issue:
public class Program {
public void randomMethod() { //method scope starts
string str2 = "Random";
str.ToUpper(); //this line shows no errors
} //method scope ends
string str = "Random"; //this is a class field, but is missing an accessibility level
str.ToLower(); //this line SHOULD show an error, because you can't do this in a class
}
Related
I fully understand why this is happening, but I don't know how to solve it as my attempts all didn't work.
I'm loading a file using MsgReader. I need to catch exceptions.
try
{
var message = MsgReader.Mime.Message.Load(fileInfo);
}
catch(IOException e)
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (message.Attachments != null) //if has attachments
{
//...
This obviously fails as the object is created within the try. How can I instantiate the object but without having it load the file?
I've tried this before the try:
var message = new MsgReader.Mime.Message;
Error:
Severity Code Description Project File Line Suppression State
Error CS1526 A new expression requires an argument list or (), [], or {} after type
I've also tried variations of this, but I can't find the type I need to specify.
As the error states, if you want to create a new object then you need parentheses to invoke the constructor:
var message = new MsgReader.Mime.Message();
However, in this case it looks like you don't actually want a new instance, but just to declare the variable:
MsgReader.Mime.Message message = null;
In this case the declaration just needs an explicit type specified because var won't be able to infer the type from just null.
Just be aware that if the code in the try fails then message will be null and can't be used/dereferenced.
(And, of course, remove the var keyword when assigning a value to the variable within the try block.)
I have a C# class with a field and a property that looks like this.
public static class Config {
// ...
private static string admin_email;
public static string AdminEmail {
get {
if (admin_email == null) {
admin_email = config_xml.Element("admin_email").Value;
// ^ The exception is thrown here.
}
return admin_email;
}
}
}
In the above code, config_xml is an XElement which contains a child element that looks like
<admin_email>myemail#example.com</admin_email>
However, when I try to access this property, I get a NullReferenceException even though the debugger shows that nothing is null.
I checked the debugger, and watching config_xml.Element("admin_email").Value shows the email, as expected.
The weird part is that when I put a breakpoint on that line and step in one step at a time there is no exception thrown.
I have tried with and without enabling the option Just My Code.
In case this helps, I try to access the property on a line like this (from a different project)
message.From = new MailAddress(Config.AdminEmail);
Edit
After changing the code to this, I realised that c was still null.
get {
if (admin_email == null) {
XElement c = config_xml;
XElement e = c.Element("admin_email");
// ^ Exception is now thrown here
string v = e.Value;
admin_email = v;
}
return admin_email;
}
Thank you David, asawyer, and Lasse V. Karlsen for helping me realise my mistake. I changed my code to this, and now it works.
admin_email = new Email(ConfigXml.Element("admin_email").Value;
I was using a similar technique for config_xml and ConfigXml, so I would only load the XML into the field config_xml if it was ever needed, and I forgot to access it with the property ConfigXml (which did the loading) instead of the field config_xml (which was null until I used the property).
I don't know why it was working with a breakpoint, maybe when I watched the property it assigned it? I don't know.
I'm using VS2015 on Windows 7.
Code analysis rule CA1804 (http://msdn.microsoft.com/library/ms182278.aspx) states that I am not using a variable and to remove it. However, I am using this variable further down in my code. This is happening across the whole solution in hundreds of places. The code block looks like this:
[WebMethod]
public bool ValidateUser(string userName, string password)
{
string soapResult = String.Empty;
try
{
// code here
using (StreamReader rd = new StreamReader(responseStream))
{
soapResult = rd.ReadToEnd();
}
// code here
bool isValidated = true;
}
catch (Exception e)
{
// throw error
}
return isValidated;
}
I'm getting this error from Code Analysis:
Error CA1804 'ValidateUser(string, string)' declares a variable, 'soapResult', of type 'string', which is never used or is only assigned to. Use this variable or remove it.
Is there something I'm missing here? It's not within an if/else like some of the instances I'm getting this error. But I figured that if it's being used at all this error would not be thrown.
Thanks for any help.
Read the analysis message carefully, note the bit I have highlighted:
Error CA1804 'ValidateUser(string, string)' declares a variable, 'soapResult', of type 'string', which is never used or is only assigned to. Use this variable or remove it.
It is telling you that you only assign a value to it (you actually do that twice including the initialisation to string.Empty) but you never use the value. So it's effectively a waste of a variable.
What you should be doing is either using the value, for example:
soapResult = rd.ReadToEnd();
if(soapResult.Contains("something")
{
isValidated = true;
}
else
{
//Not needed but added it to better show how this works in context
isValidated = false;
}
Or remove it altogether and discard the result you get from the StreamReader:
rd.ReadToEnd();
Im trying to use this function but getting some errors:
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return string.Empty;
}
static void Main(string[] args)
{
const string path = #"C:\link to foobar.lnk";
Console.WriteLine(GetShortcutTargetFile(path));
}
The first error is on the line :
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
On the right hand of the line (Shell32.ShellLinkObject)folderItem.GetLink
Im getting errors:
Error 2 One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?
And on the line in the end:
Console.WriteLine(GetShortcutTargetFile(path));
The error is on the: GetShortcutTargetFile(path) the function was static but i removed the static and then i mgetting the error in the last line.
Error 4 An object reference is required for the non-static field, method, or property 'GatherLinks.Form1.GetShortcutTargetFile(string)
How can i fix all the errors and how to get all the shortucts that target files ?
First error: add a reference to Shell32.dll in your project settings.
Second error: Where are you placing the two functions? It seems like you are trying to create the functions within a Form. That is why you can not access the "GatherLinks.Form1.GetShortcutTargetFile(string)".
Move your code from the main function to the Form loaded event and you will be able to compile :)
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.