Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm new here. I have a question for you, maybe just easy, but I can't do it well. I have a few fields in my class:
public Player player;
public Run run;
And a code:
public void doit(string method)
{
foreach (var prop in this.GetType().GetFields())
{
foreach (var meth in prop.FieldType.GetMethods())
{
if (meth.Name == method)
{
meth.Invoke(prop, null);
}
}
}
But when I'm trying to run this problem, I have a error while running:
Object does not match target type.
In line:
meth.Invoke(prop, null);
Error appears, because "prop" isn't an Class object.
When i'm trying to do this:
Player testPlayer;
testPlayer = prop;
I have an error:
'System.Reflection.FieldInfo' to 'WindowsFormsApplication.Player'
I tried many things, but nothing work.
Can you help me plz? It's important for me :)
Thanks.
You're trying to invoke the method passing in the actual FieldInfo object, rather than the value of the field.
A simple fix would be:
if (meth.Name == method)
{
meth.Invoke(prop.GetValue(this), null);
}
However, if you're trying to find a method by name, there's an easier way:
public void doit(string method)
{
foreach (var prop in this.GetType().GetFields())
{
// Get the method by name
var meth = prop.FieldType.GetMethod(method);
if (meth != null)
{
meth.Invoke(prop.GetValue(this), null);
}
}
}
Sounds like you need to get the value of that property:
meth.Invoke(prop.GetValue(this), null);
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
trying to run a function that would remove a character from a list of lists but getting a stackoverflow exception
in the program
public static void removeChar(World World)
{
Console.Clear();
Console.WriteLine("what character would you like to remove");
string cName = Console.ReadLine();
World.RemoveChar(cName);
}
in the class world
public void RemoveChar(string cName)
{
RemoveChar(cName);
}
in the class party
public void RemoveChar(string cName)
{
Node<Character> temp = Characters;
while (!temp.HasNext())
{
if (temp.GetNext().GetValue().getName() == cName)
{
temp.SetNext(temp.GetNext().GetNext());
}
temp = temp.GetNext();
}
if (temp.GetValue().getName() == cName)
{
temp = null;
}
}
when trying to remove a chracter im getting a stack overflow error
the error code im getting
side note : this is not a syntax error but an error in cmd incase it isnt clear
the properties of the class world
private string name;
private Node<Party> Partylist;
the properties of the class party
private string pName;
private Node<Character> Characters;
World.RemoveChar() seemingly by your example anyway.
Is just calling itself resulting in an infinite callstack until it overflows.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I am new to C#. The next line of code is not executing in my small program and I am unable to figure out why.
Main method
static void Main(string[] args)
{
Console.WriteLine("Loan Approval Software");
Customer inputCustomer = new Customer();
inputCustomer.Name = Console.ReadLine();
Console.WriteLine($"Hello {inputCustomer.Name}");
}
Class
public class Customer
{
// property
public string? Name { get; set; }
}
I just ran your code and it worked fine.
Please note this line: inputCustomer.Name = Console.ReadLine();
Will halt code execution until you enter in a name to the CLI.
You can see below it worked just fine. If you are getting some kind of other error or have questions about a specific line feel free to comment, but so far code is running as it should.
EDIT FOR DEMO
static void Main(string[] args)
{
while(true)
{
Console.WriteLine("Loan Approval Software");
Customer inputCustomer = new Customer();
inputCustomer.Name = Console.ReadLine();
Console.WriteLine($"Hello {inputCustomer.Name}");
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm just wondering...Why doesn't C# allow multiple return values?
At the moment we express out intent to return multiple values via returning a class or using out - as shown below.
static void Check(MyTask task )
{
if (GoodReasonsNotTo(task))
{
throw new ApplicationException("There are good reasons not to do this.");
}
}
public static int UglyDo( MyTask task, out string response )
{
Check(task);
//...
response = "Done";
return 7;
}
static void Main(string[] args)
{
var task = new MyTask("Add multiple return values");
string response;
var err = UglyDo(task, out reponse));
}
The code above could be expressed differently:
static void Check(MyTask task )
{
if (GoodReasonsNotTo(task))
{
throw new ApplicationException("There are good reasons not to do this.");
}
}
public static (int, string) PrettyDo(MyTask task)
{
Check(task);
//...
return 7, "Done.";
}
static void Main(string[] args)
{
var task = new MyTask("Add multiple return values");
var (err, response) = PrettyDo(task);
}
Is there anything special about return values vs function parameters? The look the same, they do the same things. Why weren't they made equal?
Also, could it support it the future?
BTW. The StackOverflow's syntax highlighter deals with it nicely - this surely means it would be a good thing.
Funny that you ask. It was just announced that it will be supported in C# 7.0 [MSDN]
Good question. This is actually currently supported by some higher-level languages (like Go) as well as at least some assembly languages, such as MIPS, which reserves several registers for arguments as well as two for return values (but this is at least partially convention rather than some actual physical difference between the registers). In that more general sense, there isn't anything particularly "special" about return values.
In terms of why this isn't directly supported in C# yet, I'm speculating a little here but C#'s still heavily geared towards object-oriented development. Even features like anonymous functions are implemented "under the hood" in an object-oriented manner, so I suspect that if they do end up doing something like multiple return values in the future it'll also essentially be syntactic sugar for creating and returning an object. So, basically, you're explicitly returning an object now and maybe in the future it'll implicitly return one.
Edit: Right now the closest we get to multiple return values is probably Tuples, which unfortunately has very inconvenient syntax in C# right now (they're far more convenient to use in some other .NET languages, notably F#, which I'd really like to see gain more prominence, but that's just my opinion I guess). Apparently they're looking at improving that in future versions of C#, which could be as close as we're going to get for awhile (which I suppose would be in keeping with my suspicion that whatever they do in terms of multiple return values will just be syntactic sugar for an object).
I'm still a novice in C#, but wouldn't a workaround like this help you?
Create a new class with the parameters desired and create a function returning that class.
public static testClass PrettyDo(MyTask task)
{
Check(task);
//...
testClass answer = new testClass();
answer.param1 = 7;
answer.param2 = "Done.";
return answer;
}
public class testClass
{
public int param1 { get; set; }
public string param2 { get; set; }
}
How about using Tuple:
public static Tuple<int, string> PrettyDo(MyTask task)
{
Check(task);
//...
return Tuple.Create(7, "Done.");
}
static void Main(string[] args)
{
var task = new MyTask("Add multiple return values");
var result = PrettyDo(task);
var err = result.Item1;
var response = result.Item2;
}
It doesn't support unpacking like some higher level languages, but it's pretty close to what you're after.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it a good idea to wrap the return value of the functions in a class. It provides ease of coding and you can avoid try...catch
I'm taking about doing something like this.
public class ResultWrapper
{
public bool Success{get;set;}
public Exception ErrorMessage{get;set;}
public object Result{get;set;} //not object essentially(any type)
public Result()
{
Success=false;
ErrorMessage="";
Result=null;
}
}
public ResultWrapper DoSomething(parameters....)
{
var result=new ResultWrapper()
try
{
}
catch(Exception ex)
{
result.Error=ex;
}
return result;
}
and then calling it like
static void main()
{
var result=DoSomething(parameters...);
if(result.Success)
{
//Carry on with result.Result;
}
else
{
//Log the exception or whatever... result.Error
}
}
EDIT:
consider this
static void main()
{
var result=Login(); //throws an exception
if(result.Success)
{
//retrive the result
//carry on
result=PostSomeStuff(parameter);
if(result.Success)
{
}
else
{
Console.WriteLine("Unable to Post the data.\r\nError: {0}",result.Error.Message);
}
}
else
{
Console.WriteLine("Unable to login.\r\nError: {0}",result.Error.Message);
}
}
isn't it simpler then to wrapping a try..catch outside of each function???
static void main()
{
try
{
var result=Login();
var result1=result=PostSomeStuff(parameter);
// a lot of functions doing seprate things.
}
catch(Exception ex)
{
//what to do...?
}
}
No, this is an anti-pattern. If there is any exception that you don't know how to handle then let it propagate up. Returning exception objects in the return value is a very bad idea when the language has support for exceptions.
If the method is successful it should return the value directly; if it fails it should throw an exception. (Caveat: Some methods might return bool indicating success or failure, and store the result in an out parameter. For example, int.TryParse(), Dictionary<TKey, TValue>.TryGetValue(), etc. Since exceptions can be expensive, some operations might be better suited to simply return a flag indicating failure if failure is expected to be frequent, but this should be a rare occurrence.)
Generally no. There may be specific cases where it's a good idea, but I wouldn't recommend it as a default.
It will make it impossible to allow the exception to "bubble up" until it gets to a good place to handle it. It will make the code harder to understand.
This is awful. Think how many if statement would be added to your code, just to check if an exception was thrown.
Also, think of it this way: if this were a great idea, then the .NET Framework itself would do this. Have you ever seen this pattern anywhere in .NET? I haven't.
You should almost always match the semantics of what the framework does that you are using, otherwise you end up with a weird mish-mash. Soon you have 10 competing coding "standards."
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have the following method which returns a number:
public int basketContents()
{
int basketContains = basket.Count();
return basketContains;
}
If I run this method in Main it works fine, however when I use it in a different form in the project it returns 0, regardless of what the actual number should be.
I've called it in the other form like this:
Main Main = new Main();
MessageBox.Show("Basket Contents: " + Main.basketContents(), "Information",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
If I set 'basketContains' to a number myself it will display the number fine in either form. However, when I use the count method it doesn't work.
I guess basket is not static. So in this case it will be null if you call it from another form, cause its a new variable with its default value (->empty so Count will be zero)
Main Main = new Main(); // Im a total new Form. I dont know anything, all my propertys are defaultvalues
Note: The answer is not "make it static". There a much better ways depending on your needs (f.e more parameters, events etc)
Example:
public int basketContents(List<string> myBasket)
{
if (myBasket != null)
{
int basketContains = myBasket.Count();
return basketContains;
}
return 0;
}
call it:
Main mytest = new Main();
var temp = new List<string>();
temp.Add("test");
MessageBox.Show("Basket Contents: " + myTest.basketContents(temp), "Information");
If basket is a member variable of class Main then you will need to set it after creating an instance of Main.
Also bad idea to call a variable the same name as a class.
Something like this should work:
Main myMain = new Main();
myMain.basket.Items.Add("Whatever");
MessageBox.Show("Basket Contents: " + Main.basketContents(), "Information",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);